Apache HttpComponents在App里访问HTTP服务
生活随笔
收集整理的這篇文章主要介紹了
Apache HttpComponents在App里访问HTTP服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
服務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.java
package 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{//服務URLString 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="提交" οnclick="onSubmit()"><br><br></div></body> </html>HelloServlet.java
package 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="清華大學出版社";//構造JSONJSONObject 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) //最多讀取16KBbreak;}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);//構造JSONJSONObject 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}}總結
以上是生活随笔為你收集整理的Apache HttpComponents在App里访问HTTP服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 获取上周_上周惠州13盘预售9盘价格涨了
- 下一篇: 职工工资信息系统 c语言题,工资信息管理