日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

Apache HttpComponents在App里访问HTTP服务

發(fā)布時間:2025/3/15 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Apache HttpComponents在App里访问HTTP服务 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

服務(wù)URL:http://127.0.0.1:8080/myweb/servlet/HelloServlet在任意APP里,都可以通過HTTP來訪問這個服務(wù);


Java的App項目里,可以使用apache.org下的一個庫來完成HTTP交互。


注意:

1.在服務(wù)器端,建議使用Content-Length方式來發(fā)送應(yīng)答;

2.在客戶端,HttpEntity表示發(fā)送/接收的數(shù)據(jù)內(nèi)容,含Content-Type, Content-Length, charset 和正文信息;

3.EntityUtils不能接收chunked方式的數(shù)據(jù)


使用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{//服務(wù)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);//上行數(shù)據(jù)StringEntity dataSent=new StringEntity(reqText,ContentType.create("text/plain","UTF-8"));httppost.setEntity(dataSent);CloseableHttpResponse response=httpclient.execute(httppost);try {//下行數(shù)據(jù)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();}}}


服務(wù)器端:

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",//指明下行數(shù)據(jù)的格式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("服務(wù)器錯誤: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="清華大學(xué)出版社";//構(gòu)造JSONJSONObject jsReply=new JSONObject();jsReply.put("title", title);jsReply.put("author", author);jsReply.put("isbn", isbn);jsReply.put("publisher", publisher);String replyText=jsReply.toString();//應(yīng)答,方便客戶端解析,采用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 中讀取時,要反復(fù)讀取,直接讀完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);//構(gòu)造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}}

總結(jié)

以上是生活随笔為你收集整理的Apache HttpComponents在App里访问HTTP服务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。