您的位置:首页 > 理论基础 > 计算机网络

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 HttpComponents App
相关文章推荐