java发送HttpClient请求及接收请求结果过程的简单实例
一.
1、写一个httprequestutils工具类,包括post请求和get请求
package com.brainlong.framework.util.httpclient; import net.sf.json.jsonobject; import org.apache.commons.httpclient.httpstatus; import org.apache.http.httpresponse; import org.apache.http.client.methods.httpget; import org.apache.http.client.methods.httppost; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.defaulthttpclient;import org.apache.http.util.entityutils; import org.slf4j.logger; import org.slf4j.loggerfactory; import java.io.ioexception;import java.net.urldecoder; public class httprequestutils { private static logger logger = loggerfactory.getlogger(httprequestutils.class); //日志记录 /** * httppost * @param url 路径 * @param jsonparam 参数 * @return */ public static jsonobject httppost(string url,jsonobject jsonparam){ return httppost(url, jsonparam, false); } /** * post请求 * @param url url地址 * @param jsonparam 参数 * @param noneedresponse 不需要返回结果 * @return */ public static jsonobject httppost(string url,jsonobject jsonparam, boolean noneedresponse){ //post请求返回结果 defaulthttpclient httpclient = new defaulthttpclient(); jsonobject jsonresult = null; httppost method = new httppost(url); try { if (null != jsonparam) { //解决中文乱码问题 stringentity entity = new stringentity(jsonparam.tostring(), "utf-8"); entity.setcontentencoding("utf-8"); entity.setcontenttype("application/json"); method.setentity(entity); } httpresponse result = httpclient.execute(method); url = urldecoder.decode(url, "utf-8"); /**请求发送成功,并得到响应**/ if (result.getstatusline().getstatuscode() == 200) { string str = ""; try { /**读取服务器返回过来的json字符串数据**/ str = entityutils.tostring(result.getentity()); if (noneedresponse) { return null; } /**把json字符串转换成json对象**/ jsonresult = jsonobject.fromobject(str); } catch (exception e) { logger.error("post请求提交失败:" + url, e); } } } catch (ioexception e) { logger.error("post请求提交失败:" + url, e); } return jsonresult; } /** * 发送get请求 * @param url 路径 * @return */ public static jsonobject httpget(string url){ //get请求返回结果 jsonobject jsonresult = null; try { defaulthttpclient client = new defaulthttpclient(); //发送get请求 httpget request = new httpget(url); httpresponse response = client.execute(request); /**请求发送成功,并得到响应**/ if (response.getstatusline().getstatuscode() == httpstatus.sc_ok) { /**读取服务器返回过来的json字符串数据**/ string strresult = entityutils.tostring(response.getentity()); /**把json字符串转换成json对象**/ jsonresult = jsonobject.fromobject(strresult); url = urldecoder.decode(url, "utf-8"); } else { logger.error("get请求提交失败:" + url); } } catch (ioexception e) { logger.error("get请求提交失败:" + url, e); } return jsonresult; }}
2、写业务代码发送http请求
3、mvc配置文件设置controller扫描目录
<!-- 自动扫描且只扫描@controller --> <context:component-scan base-package="com.wiselong.multichannel" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.controller" /> </context:component-scan>
4、接收http请求
接收post请求
@controller @requestmapping(value = "/api/platform/exceptioncenter/exceptioninfo") public class exceptioninfocontroller { //注入 @autowired private exceptioninfobiz exceptioninfobiz; /** * 创建异常信息请求 * @param requestbody 请求消息内容 * @param request 请求消息头 * @return jsonobject */ @requestmapping( value="/create", method = requestmethod.post ) public modelandview createexceptioninfo(@requestbody string requestbody, httpservletrequest request) { jsonobject jsonobject = jsonobject.fromobject(requestbody); comexceptioninfo comexceptioninfo = new comexceptioninfo(); comexceptioninfo.setprojectname(jsonobject.getstring("projectname")); comexceptioninfo.settagname(jsonobject.getstring("tagname")); exceptioninfobiz.insert(comexceptioninfo); //返回请求结果 jsonobject result= new jsonobject(); result.put("success", "true"); return new modelandview("", responseutilshelper.jsonsuccess(result.tostring())); } }
接收get请求
@controller @requestmapping(value="/api/platform/messagecenter/messages/sms") public class smscontroller { @autowired smssendbiz smssendbiz; /** * 接收手机号码和内容往短信发送表插入一条记录 * @param requestbody 请求消息内容 * @param request 请求消息头 * @return jsonobject */ @requestmapping( value="/send", method= requestmethod.get ) public modelandview sendsms(@requestbody string requestbody, httpservletrequest request) { //获取请求url及url后面传输的参数 string url = request.getrequesturl() + "?" + request.getquerystring(); url = buildrequesturl.decodeurl(url); string telephone = requestutils.getstringvalue(request, "telephone"); string content = requestutils.getstringvalue(request, "content"); smssendbiz.insertttmsquequ(telephone,content); return new modelandview("", responseutilshelper.jsonresult("", true)); } }
二.
get
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import org.apache.commons.httpclient.httpclient; import org.apache.commons.httpclient.httpmethod; import org.apache.commons.httpclient.methods.getmethod; public class h_client_get { public static void main(string[] args) throws ioexception { // new类对象 httpclient client = new httpclient(); // 使用 get 方法 与url服务器进行交互 // httpmethod method = new getmethod("http://192.168.111.128/bak/regist.php?email=admin@admin.com&password=1234567&re_password=1234567&username=admin&nickname=管理员"); httpmethod method = new getmethod("http://192.168.111.128/bak/login.php?username="); // 使用 get 方法 ,实行与url服务器连接 client.executemethod(method); // 数据流输出 // method.getresponsebodyasstream 创建字节流对象为inputstream inputstream inputstream = method.getresponsebodyasstream(); // inputstreamreader(inputstream)字节流转换成字符流 bufferedreader封装成带有缓冲的字符流对象了 bufferedreader br = new bufferedreader(new inputstreamreader(inputstream,"utf-8")); // stringbuffer是字符串变量,它的对象是可以扩充和修改的 创建一个空的stringbuffer类的对象 stringbuffer stringbuffer = new stringbuffer(); // 定义字符串常量 string str= ""; // br字符流赋值给str字符串常量 str不等于空 按行输出 while((str = br.readline()) != null){ // stringbuffer 是字符串变量,它的对象是可以扩充和修改的 将str数据赋予 stringbuffer stringbuffer .append(str ); } // 按照字符串循环输出stringbuffer system.out.println(stringbuffer.tostring()); // 关闭method 的 httpclient连接 method.releaseconnection(); } }
post
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import org.apache.commons.httpclient.methods.postmethod; import org.apache.commons.httpclient.*; public class h_client_post { public static void main(string[] args) throws ioexception { httpclient client = new httpclient(); postmethod method = new postmethod("http://192.168.111.128/bak/login_post.php"); //表单域的值,既post传入的key=value namevaluepair[] date = { new namevaluepair("username","admin"),new namevaluepair("password","123457")}; //method使用表单阈值 method.setrequestbody(date); //提交表单 client.executemethod(method); //字符流转字节流 循环输出,同get解释 inputstream inputstream = method.getresponsebodyasstream(); bufferedreader br = new bufferedreader(new inputstreamreader(inputstream,"utf-8")); stringbuffer stringbuffer = new stringbuffer(); string str= ""; while((str = br.readline()) != null){ stringbuffer .append(str ); } system.out.println(stringbuffer.tostring()); method.releaseconnection(); } }
三.
http协议的重要性相信不用我多说了,httpclient相比传统jdk自带的urlconnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送http请求变得容易,而且也方便了开发人员测试接口(基于http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握httpclient是很重要的必修内容,掌握httpclient后,相信对于http协议的了解会更加深入。
一、简介
httpclient是apache jakarta common下的子项目,用来提供高效的、最新的、功能丰富的支持http协议的客户端编程工具包,并且它支持http协议最新的版本和建议。httpclient已经应用在很多的项目中,比如apache jakarta上很著名的另外两个开源项目cactus和htmlunit都使用了httpclient。
二、特性
1. 基于标准、纯净的java语言。实现了http1.0和http1.1
2. 以可扩展的面向对象的结构实现了http全部的方法(get, post, put, delete, head, options, and trace)。
3. 支持https协议。
4. 通过http代理建立透明的连接。
5. 利用connect方法通过http代理建立隧道的https连接。
6. basic, digest, ntlmv1, ntlmv2, ntlm2 session, snpnego/kerberos认证方案。
7. 插件式的自定义认证方案。
8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
10. 自动处理set-cookie中的cookie。
11. 插件式的自定义cookie策略。
12. request的输出流可以避免流中内容直接缓冲到socket服务器。
13. response的输入流可以有效的从socket服务器直接读取相应内容。
14. 在http1.0和http1.1中利用keepalive保持持久连接。
15. 直接获取服务器发送的response code和 headers。
16. 设置连接超时的能力。
17. 实验性的支持http1.1 response caching。
18. 源代码基于apache license 可免费获取。
三、使用方法
使用httpclient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建httpclient对象。
2. 创建请求方法的实例,并指定请求url。如果需要发送get请求,创建httpget对象;如果需要发送post请求,创建httppost对象。
3. 如果需要发送请求参数,可调用httpget、httppost共同的setparams(hetpparams params)方法来添加请求参数;对于httppost对象而言,也可调用setentity(httpentity entity)方法来设置请求参数。
4. 调用httpclient对象的execute(httpurirequest request)发送请求,该方法返回一个httpresponse。
5. 调用httpresponse的getallheaders()、getheaders(string name)等方法可获取服务器的响应头;调用httpresponse的getentity()方法可获取httpentity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
四、实例
package com.test; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.unsupportedencodingexception; import java.security.keymanagementexception; import java.security.keystore; import java.security.keystoreexception; import java.security.nosuchalgorithmexception; import java.security.cert.certificateexception; import java.util.arraylist; import java.util.list; import javax.net.ssl.sslcontext; import org.apache.http.httpentity; import org.apache.http.namevaluepair; import org.apache.http.parseexception; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.entity.urlencodedformentity; 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.conn.ssl.sslconnectionsocketfactory; import org.apache.http.conn.ssl.sslcontexts; import org.apache.http.conn.ssl.trustselfsignedstrategy; import org.apache.http.entity.contenttype; import org.apache.http.entity.mime.multipartentitybuilder; import org.apache.http.entity.mime.content.filebody; import org.apache.http.entity.mime.content.stringbody; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.impl.client.httpclients; import org.apache.http.message.basicnamevaluepair; import org.apache.http.util.entityutils; import org.junit.test; public class httpclienttest { @test public void junittest() { get(); } /** * httpclient连接ssl */ public void ssl() { closeablehttpclient httpclient = null; try { keystore truststore = keystore.getinstance(keystore.getdefaulttype()); fileinputstream instream = new fileinputstream(new file("d:\\tomcat.keystore")); try { 54. // 加载keystore d:\\tomcat.keystore truststore.load(instream, "123456".tochararray()); } catch (certificateexception e) { e.printstacktrace(); } finally { try { instream.close(); } catch (exception ignore) { } } // 相信自己的ca和所有自签名的证书 sslcontext sslcontext = sslcontexts.custom().loadtrustmaterial(truststore, new trustselfsignedstrategy()).build(); // 只允许使用tlsv1协议 sslconnectionsocketfactory sslsf = new sslconnectionsocketfactory(sslcontext, new string[] { "tlsv1" }, null, sslconnectionsocketfactory.browser_compatible_hostname_verifier); httpclient = httpclients.custom().setsslsocketfactory(sslsf).build(); // 创建http请求(get方式) httpget httpget = new httpget("https://localhost:8443/mydemo/ajax/serivcej.action"); system.out.println("executing request" + httpget.getrequestline()); closeablehttpresponse response = httpclient.execute(httpget); try { httpentity entity = response.getentity(); system.out.println("----------------------------------------"); system.out.println(response.getstatusline()); if (entity != null) { system.out.println("response content length: " + entity.getcontentlength()); system.out.println(entityutils.tostring(entity)); entityutils.consume(entity); } } finally { response.close(); } } catch (parseexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } catch (keymanagementexception e) { e.printstacktrace(); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } catch (keystoreexception e) { e.printstacktrace(); } finally { if (httpclient != null) { try { httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } } } /** * post方式提交表单(模拟用户登录请求) */ public void postform() { // 创建默认的httpclient实例. closeablehttpclient httpclient = httpclients.createdefault(); // 创建httppost httppost httppost = new httppost("http://localhost:8080/mydemo/ajax/serivcej.action"); // 创建参数队列 list<namevaluepair> formparams = new arraylist<namevaluepair>(); formparams.add(new basicnamevaluepair("username", "admin")); formparams.add(new basicnamevaluepair("password", "123456")); urlencodedformentity uefentity; try { uefentity = new urlencodedformentity(formparams, "utf-8"); httppost.setentity(uefentity); system.out.println("executing request " + httppost.geturi()); closeablehttpresponse response = httpclient.execute(httppost); try { httpentity entity = response.getentity(); if (entity != null) { system.out.println("--------------------------------------"); system.out.println("response content: " + entityutils.tostring(entity, "utf-8")); system.out.println("--------------------------------------"); } } finally { response.close(); } } catch (clientprotocolexception e) { e.printstacktrace(); } catch (unsupportedencodingexception e1) { e1.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } } /** * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 */ public void post() { // 创建默认的httpclient实例. closeablehttpclient httpclient = httpclients.createdefault(); // 创建httppost httppost httppost = new httppost("http://localhost:8080/mydemo/ajax/serivcej.action"); // 创建参数队列 list<namevaluepair> formparams = new arraylist<namevaluepair>(); formparams.add(new basicnamevaluepair("type", "house")); urlencodedformentity uefentity; try { uefentity = new urlencodedformentity(formparams, "utf-8"); httppost.setentity(uefentity); system.out.println("executing request " + httppost.geturi()); closeablehttpresponse response = httpclient.execute(httppost); try { httpentity entity = response.getentity(); if (entity != null) { system.out.println("--------------------------------------"); system.out.println("response content: " + entityutils.tostring(entity, "utf-8")); system.out.println("--------------------------------------"); } } finally { response.close(); } } catch (clientprotocolexception e) { e.printstacktrace(); } catch (unsupportedencodingexception e1) { e1.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } } /** * 发送 get请求 */ public void get() { closeablehttpclient httpclient = httpclients.createdefault(); try { // 创建httpget. httpget httpget = new httpget("http://www.baidu.com/"); system.out.println("executing request " + httpget.geturi()); // 执行get请求. closeablehttpresponse response = httpclient.execute(httpget); try { // 获取响应实体 httpentity entity = response.getentity(); system.out.println("--------------------------------------"); // 打印响应状态 system.out.println(response.getstatusline()); if (entity != null) { // 打印响应内容长度 system.out.println("response content length: " + entity.getcontentlength()); // 打印响应内容 system.out.println("response content: " + entityutils.tostring(entity)); } system.out.println("------------------------------------"); } finally { response.close(); } } catch (clientprotocolexception e) { e.printstacktrace(); } catch (parseexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } } /** * 上传文件 */ public void upload() { closeablehttpclient httpclient = httpclients.createdefault(); try { httppost httppost = new httppost("http://localhost:8080/mydemo/ajax/serivcefile.action"); filebody bin = new filebody(new file("f:\\image\\sendpix0.jpg")); stringbody comment = new stringbody("a binary file of some kind", contenttype.text_plain); httpentity reqentity = multipartentitybuilder.create().addpart("bin", bin).addpart("comment", comment).build(); httppost.setentity(reqentity); system.out.println("executing request " + httppost.getrequestline()); closeablehttpresponse response = httpclient.execute(httppost); try { system.out.println("----------------------------------------"); system.out.println(response.getstatusline()); httpentity resentity = response.getentity(); if (resentity != null) { system.out.println("response content length: " + resentity.getcontentlength()); } entityutils.consume(resentity); } finally { response.close(); } } catch (clientprotocolexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally { try { httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } } }</namevaluepair></namevaluepair></namevaluepair></namevaluepair>
以上这篇java发送httpclient请求及接收请求结果过程的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇: JAVA JNI函数的注册过程详细介绍