Apache HttpComponents在App里访问HTTP服务
2018-02-11 21:23
417 查看
服务URL:http://127.0.0.1:8080/myweb/servlet/HelloServlet在任意APP里,都可以通过HTTP来访问这个服务;
Java的App项目里,可以使用apache.org下的一个库来完成HTTP交互。
注意:
1.在服务器端,建议使用Content-Length方式来发送应答;
2.在客户端,HttpEntity表示发送/接收的数据内容,含Content-Type, Content-Length, charset 和正文信息;
3.EntityUtils不能接收chunked方式的数据
使用GET方式:
使用POST方式:
客户端
HelloWordl.javapackage my;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HelloWorld {
//HTTP GET测试
public static String test1()throws Exception{
//服务URL
String url="http://127.0.0.1:8080/myweb/servlet/HelloServlet?isbn=1001";
CloseableHttpClient httpclient=HttpClients.createDefault();
HttpGet httpget=new HttpGet(url);
CloseableHttpResponse response=httpclient.execute(httpget);
try {
HttpEntity entity=response.getEntity();
if(entity!=null) {
long len=entity.getContentLength();
if(len!=-1&&len<16384) {
String replyText=EntityUtils.toString(entity);
return replyText;
}
else {
//Stream content out
}
}
}
finally {
response.close();
}
return null;
}
//HTTP POST测试
public static String test2() throws Exception{
String url="http://127.0.0.1:8080/myweb/servlet/HelloServlet";
String reqText="{ some data }";
CloseableHttpClient httpclient=HttpClients.createDefault();
HttpPost httppost=new HttpPost(url);
//上行数据
StringEntity dataSent=new StringEntity(reqText,ContentType.create("text/plain","UTF-8"));
httppost.setEntity(dataSent);
CloseableHttpResponse response=httpclient.execute(httppost);
try {
//下行数据
HttpEntity dataRecv=response.getEntity();
if(dataRecv!=null) {
long len=dataRecv.getContentLength();
if(len!=-1&&len<16384) {
String replyText=EntityUtils.toString(dataRecv);
return replyText;
}
else {
//Stream content out
}
}
}
finally {
response.close();
}
return null;
}
public static void main(String[] args) {
try {
String replyText=test2();
System.out.println("-----Reply-----\n"+replyText);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
服务器端:
index,jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src="jquery/jquery.js"></script>
<script src="bootstrap/js/bootstrap,min.js"></script>
<script src="jquery/jquery.json-2.3.js"></script>
<script>
function trace(msg){
try{
console.log(msg);
}
catch(err){
}
}
function onSubmit(){
jQuery.ajax({
method:"POST",
url:"servlet/HelloServlet",
//指明下行数据的格式
dataType:"json",
success:function(data,textStatus,jqXHR){
showResult(data);
},
error:function(jqXHR,textStatus,errorThrown){
$("#result").html("error:"+errorThrown);
}
});
}
//显示到表格里
function showResult(result){
if(result.error==0){
alert("成功");
}
else{
alert("服务器错误:error="+result.error+",reason"+result.reason);
}
}
//页面加载后的初始化工作
$(document).ready(function(){
});
</script>
</head>
<body>
<div class="container">
<br>
<input type="button" value="提交" onclick="onSubmit()">
<br>
<br>
</div>
</body>
</html>
HelloServlet.javapackage my;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
public class HelloServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public HelloServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String isbn=request.getParameter("isbn");
String title="如何与SB相处";
String author="XXXXX";
String publisher="清华大学出版社";
//构造JSON
JSONObject jsReply=new JSONObject();
jsReply.put("title", title);
jsReply.put("author", author);
jsReply.put("isbn", isbn);
jsReply.put("publisher", publisher);
String replyText=jsReply.toString();
//应答,方便客户端解析,采用Content-Length方式
byte[] outdata=replyText.getBytes("UTF-8");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.setContentLength(outdata.length);
OutputStream out=response.getOutputStream();
out.write(outdata);
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
//从TCP Stream 中读取时,要反复读取,直接读完
public String readAsText(InputStream streamIn,String charset) throws IOException{
ByteArrayOutputStream cache=new ByteArrayOutputStream(4096);
byte[] data=new byte[1024];
while(true){
int len=streamIn.read(data);
if(len<0)
break;
if(len==0)
continue;
//缓存起来
cache.write(data,0,len);
if(cache.size()>1024*16) //最多读取16KB
break;
}
return cache.toString(charset);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String reqText=readAsText(request.getInputStream(),"UTF-8");
System.out.println("----------请求----------\n"+reqText);
//构造JSON
JSONObject jsReply=new JSONObject();
jsReply.put("error", 0);
jsReply.put("reason", "OK");
String replyText=jsReply.toString();
//采用Content-Length方式
byte[] outdata=replyText.getBytes("UTF-8");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.setContentLength(outdata.length);
OutputStream out=response.getOutputStream();
out.write(outdata);
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
Java的App项目里,可以使用apache.org下的一个库来完成HTTP交互。
注意:
1.在服务器端,建议使用Content-Length方式来发送应答;
2.在客户端,HttpEntity表示发送/接收的数据内容,含Content-Type, Content-Length, charset 和正文信息;
3.EntityUtils不能接收chunked方式的数据
使用GET方式:
使用POST方式:
客户端
HelloWordl.javapackage my;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HelloWorld {
//HTTP GET测试
public static String test1()throws Exception{
//服务URL
String url="http://127.0.0.1:8080/myweb/servlet/HelloServlet?isbn=1001";
CloseableHttpClient httpclient=HttpClients.createDefault();
HttpGet httpget=new HttpGet(url);
CloseableHttpResponse response=httpclient.execute(httpget);
try {
HttpEntity entity=response.getEntity();
if(entity!=null) {
long len=entity.getContentLength();
if(len!=-1&&len<16384) {
String replyText=EntityUtils.toString(entity);
return replyText;
}
else {
//Stream content out
}
}
}
finally {
response.close();
}
return null;
}
//HTTP POST测试
public static String test2() throws Exception{
String url="http://127.0.0.1:8080/myweb/servlet/HelloServlet";
String reqText="{ some data }";
CloseableHttpClient httpclient=HttpClients.createDefault();
HttpPost httppost=new HttpPost(url);
//上行数据
StringEntity dataSent=new StringEntity(reqText,ContentType.create("text/plain","UTF-8"));
httppost.setEntity(dataSent);
CloseableHttpResponse response=httpclient.execute(httppost);
try {
//下行数据
HttpEntity dataRecv=response.getEntity();
if(dataRecv!=null) {
long len=dataRecv.getContentLength();
if(len!=-1&&len<16384) {
String replyText=EntityUtils.toString(dataRecv);
return replyText;
}
else {
//Stream content out
}
}
}
finally {
response.close();
}
return null;
}
public static void main(String[] args) {
try {
String replyText=test2();
System.out.println("-----Reply-----\n"+replyText);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
服务器端:
index,jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src="jquery/jquery.js"></script>
<script src="bootstrap/js/bootstrap,min.js"></script>
<script src="jquery/jquery.json-2.3.js"></script>
<script>
function trace(msg){
try{
console.log(msg);
}
catch(err){
}
}
function onSubmit(){
jQuery.ajax({
method:"POST",
url:"servlet/HelloServlet",
//指明下行数据的格式
dataType:"json",
success:function(data,textStatus,jqXHR){
showResult(data);
},
error:function(jqXHR,textStatus,errorThrown){
$("#result").html("error:"+errorThrown);
}
});
}
//显示到表格里
function showResult(result){
if(result.error==0){
alert("成功");
}
else{
alert("服务器错误:error="+result.error+",reason"+result.reason);
}
}
//页面加载后的初始化工作
$(document).ready(function(){
});
</script>
</head>
<body>
<div class="container">
<br>
<input type="button" value="提交" onclick="onSubmit()">
<br>
<br>
</div>
</body>
</html>
HelloServlet.javapackage my;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
public class HelloServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public HelloServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String isbn=request.getParameter("isbn");
String title="如何与SB相处";
String author="XXXXX";
String publisher="清华大学出版社";
//构造JSON
JSONObject jsReply=new JSONObject();
jsReply.put("title", title);
jsReply.put("author", author);
jsReply.put("isbn", isbn);
jsReply.put("publisher", publisher);
String replyText=jsReply.toString();
//应答,方便客户端解析,采用Content-Length方式
byte[] outdata=replyText.getBytes("UTF-8");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.setContentLength(outdata.length);
OutputStream out=response.getOutputStream();
out.write(outdata);
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
//从TCP Stream 中读取时,要反复读取,直接读完
public String readAsText(InputStream streamIn,String charset) throws IOException{
ByteArrayOutputStream cache=new ByteArrayOutputStream(4096);
byte[] data=new byte[1024];
while(true){
int len=streamIn.read(data);
if(len<0)
break;
if(len==0)
continue;
//缓存起来
cache.write(data,0,len);
if(cache.size()>1024*16) //最多读取16KB
break;
}
return cache.toString(charset);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String reqText=readAsText(request.getInputStream(),"UTF-8");
System.out.println("----------请求----------\n"+reqText);
//构造JSON
JSONObject jsReply=new JSONObject();
jsReply.put("error", 0);
jsReply.put("reason", "OK");
String replyText=jsReply.toString();
//采用Content-Length方式
byte[] outdata=replyText.getBytes("UTF-8");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.setContentLength(outdata.length);
OutputStream out=response.getOutputStream();
out.write(outdata);
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
相关文章推荐
- 为 Android 开发访问 JAX-RS Web 服务的 Apache HttpClient 客户端 学习创建 Apache HttpClient Android 客户端
- http服务(二)——apache基于用户名访问控制
- [乐意黎原创] 通过Apache反向代理实现多个http/https访问NodeJS服务
- linux下使用apache http server 连接 tomcat 达到使用直接apache一个服务端口就可访问php和jsp
- 已知 apache 服务的访问日志按天记录在服务器本地目录/app/logs 下,由于磁盘空间紧张,现在要求只能保留最近 7 天的访问日志!请问如何解决? 请给出解决办法或配置或处理命令。(提示:可以
- 源码编译apache实现CGI,虚拟主机,httpds安全访问,status服务状态信息,压缩等功能。
- 通过http proxy访问git 服务
- Android系统之APP访问硬件--------JNI与硬件访问服务0001
- 无法连接到http://XXX/arcgis/services 错误拒绝访问:计算机som服务为启动或som权限
- HTTP 访问接口封装,app开发中常用。
- Android模拟器访问本地的apache tomcat服务
- 无法连接到http://XXX/arcgis/services 错误拒绝访问:计算机som服务为启动或som权限
- apache服务的访问控制
- Linux Apache HTTP服务
- 【云服务器】Apache+php环境,php调用Mysql报错HTTP 500,telnet可访问数据库
- apache http server 初始配置(静态页面访问)
- 通过浏览器输入http地址访问app内部共享文件
- 构建自定义Docker镜像使用ApacheHttp服务的代理功能
- Apache 禁用IP 访问 和 HTTP 跳转 HTTPS
- android的httppost方法访问本地web服务(二)