Spring+Http请求+HttpClient实现传参
一、HttpClient简介
HTTP协议可能是现在Internet上使用得最多、最重要的协议了,越来越多的Java应用程序需要直接通过HTTP协议来访问网络资源。虽然在JDK的javanet包中已经提供了访问HTTP协议的基本功能,但是对于大部分应用程序来说,JDK库本身提供的功能还不够丰富和灵活。HttpClient是ApacheJakartaCommon下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
HTTP和浏览器有点像,但却不是浏览器。很多人觉得既然HttpClient是一个HTTP客户端编程工具,很多人把他当做浏览器来理解,但是其实HttpClient不是浏览器,它是一个HTTP通信库,因此它只提供一个通用浏览器应用程序所期望的功能子集,最根本的区别是HttpClient中没有用户界面,浏览器需要一个渲染引擎来显示页面,并解释用户输入,例如鼠标点击显示页面上的某处,有一个布局引擎,计算如何显示HTML页面,包括级联样式表和图像。javascript解释器运行嵌入HTML页面或从HTML页面引用的javascript代码。来自用户界面的事件被传递到javascript解释器进行处理。除此之外,还有用于插件的接口,可以处理Applet,嵌入式媒体对象(如pdf文件,Quicktime电影和Flash动画)或ActiveX控件(可以执行任何操作)。HttpClient只能以编程的方式通过其API用于传输和接受HTTP消息。
HttpClient的主要功能:
- 实现了所有HTTP的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS等)
- 支持HTTPS协议
- 支持代理服务器(Nginx等)等
- 支持自动(跳转)转向
二、Maven依赖
org.apache.httpcomponents httpclient 4.5.9
三、GET无参
/**
*GET---无参测试
*/
@Test
publicvoiddoGetTestOne(){
//获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClienthttpClient=HttpClientBuilder.create().build();
//创建Get请求
HttpGethttpGet=newHttpGet("http://localhost:12345/doGetControllerOne");
//响应模型
CloseableHttpResponseresponse=null;
try{
//由客户端执行(发送)Get请求
response=httpClient.execute(httpGet);
//从响应模型中获取响应实体
HttpEntityresponseEntity=response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if(responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+EntityUtils.toString(responseEntity));
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
//释放资源
if(httpClient!=null){
httpClient.close();
}
if(response!=null){
response.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
四、GET有参
拼接
/**
*GET---有参测试(方式一:手动在url后面加上参数)
*/
@Test
publicvoiddoGetTestWayOne(){
//获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClienthttpClient=HttpClientBuilder.create().build();
//参数
StringBufferparams=newStringBuffer();
try{
//字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
params.append("name="+URLEncoder.encode("&","utf-8"));
params.append("&");
params.append("age=24");
}catch(UnsupportedEncodingExceptione1){
e1.printStackTrace();
}
//创建Get请求
HttpGethttpGet=newHttpGet("http://localhost:12345/doGetControllerTwo"+"?"+params);
//响应模型
CloseableHttpResponseresponse=null;
try{
//配置信息
RequestConfigrequestConfig=RequestConfig.custom()
//设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
//设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
//socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
//设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
//将上面的配置信息运用到这个Get请求里
httpGet.setConfig(requestConfig);
//由客户端执行(发送)Get请求
response=httpClient.execute(httpGet);
//从响应模型中获取响应实体
HttpEntityresponseEntity=response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if(responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+EntityUtils.toString(responseEntity));
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
//释放资源
if(httpClient!=null){
httpClient.close();
}
if(response!=null){
response.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
URI获得HttpGet
/**
*GET---有参测试(方式二:将参数放入键值对类中,再放入URI中,从而通过URI得到HttpGet实例)
*/
@Test
publicvoiddoGetTestWayTwo(){
//获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClienthttpClient=HttpClientBuilder.create().build();
//参数
URIuri=null;
try{
//将参数放入键值对类NameValuePair中,再放入集合中
Listparams=newArrayList<>();
params.add(newBasicNameValuePair("name","&"));
params.add(newBasicNameValuePair("age","18"));
//设置uri信息,并将参数集合放入uri;
//注:这里也支持一个键值对一个键值对地往里面放setParameter(Stringkey,Stringvalue)
uri=newURIBuilder().setScheme("http").setHost("localhost")
.setPort(12345).setPath("/doGetControllerTwo")
.setParameters(params).build();
}catch(URISyntaxExceptione1){
e1.printStackTrace();
}
//创建Get请求
HttpGethttpGet=newHttpGet(uri);
//响应模型
CloseableHttpResponseresponse=null;
try{
//配置信息
RequestConfigrequestConfig=RequestConfig.custom()
//设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
//设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
//socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
//设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
//将上面的配置信息运用到这个Get请求里
httpGet.setConfig(requestConfig);
//由客户端执行(发送)Get请求
response=httpClient.execute(httpGet);
//从响应模型中获取响应实体
HttpEntityresponseEntity=response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if(responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+EntityUtils.toString(responseEntity));
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
//释放资源
if(httpClient!=null){
httpClient.close();
}
if(response!=null){
response.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
五、POST无参
/**
*POST---无参测试
*/
@Test
publicvoiddoPostTestOne(){
//获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClienthttpClient=HttpClientBuilder.create().build();
//创建Post请求
HttpPosthttpPost=newHttpPost("http://localhost:12345/doPostControllerOne");
//响应模型
CloseableHttpResponseresponse=null;
try{
//由客户端执行(发送)Post请求
response=httpClient.execute(httpPost);
//从响应模型中获取响应实体
HttpEntityresponseEntity=response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if(responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+EntityUtils.toString(responseEntity));
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
//释放资源
if(httpClient!=null){
httpClient.close();
}
if(response!=null){
response.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
六、POST有参(普通参数)
注:POST传递普通参数时,方式与GET一样即可,这里以直接在url后缀上参数的方式示例。
/**
*POST---有参测试(普通参数)
*/
@Test
publicvoiddoPostTestFour(){
//获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClienthttpClient=HttpClientBuilder.create().build();
//参数
StringBufferparams=newStringBuffer();
try{
//字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
params.append("name="+URLEncoder.encode("&","utf-8"));
params.append("&");
params.append("age=24");
}catch(UnsupportedEncodingExceptione1){
e1.printStackTrace();
}
//创建Post请求
HttpPosthttpPost=newHttpPost("http://localhost:12345/doPostControllerFour"+"?"+params);
//设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
httpPost.setHeader("Content-Type","application/json;charset=utf8");
//响应模型
CloseableHttpResponseresponse=null;
try{
//由客户端执行(发送)Post请求
response=httpClient.execute(httpPost);
//从响应模型中获取响应实体
HttpEntityresponseEntity=response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if(responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+EntityUtils.toString(responseEntity));
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
//释放资源
if(httpClient!=null){
httpClient.close();
}
if(response!=null){
response.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
七、POST有参(对象参数)
/**
*POST---有参测试(对象参数)
*/
@Test
publicvoiddoPostTestTwo(){
//获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClienthttpClient=HttpClientBuilder.create().build();
//创建Post请求
HttpPosthttpPost=newHttpPost("http://localhost:12345/doPostControllerTwo");
Useruser=newUser();
user.setName("潘晓婷");
user.setAge(18);
user.setGender("女");
user.setMotto("姿势要优雅~");
//我这里利用阿里的fastjson,将Object转换为json字符串;
//(需要导入com.alibaba.fastjson.JSON包)
StringjsonString=JSON.toJSONString(user);
StringEntityentity=newStringEntity(jsonString,"UTF-8");
//post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type","application/json;charset=utf8");
//响应模型
CloseableHttpResponseresponse=null;
try{
//由客户端执行(发送)Post请求
response=httpClient.execute(httpPost);
//从响应模型中获取响应实体
HttpEntityresponseEntity=response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if(responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+EntityUtils.toString(responseEntity));
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
//释放资源
if(httpClient!=null){
httpClient.close();
}
if(response!=null){
response.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
八、POST有参(普通参数+对象参数)
注:POST传递普通参数时,方式与GET一样即可,这里以通过URI获得HttpPost的方式为例。
/**
*POST---有参测试(普通参数+对象参数)
*/
@Test
publicvoiddoPostTestThree(){
//获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClienthttpClient=HttpClientBuilder.create().build();
//创建Post请求
//参数
URIuri=null;
try{
//将参数放入键值对类NameValuePair中,再放入集合中
Listparams=newArrayList<>();
params.add(newBasicNameValuePair("flag","4"));
params.add(newBasicNameValuePair("meaning","这是什么鬼?"));
//设置uri信息,并将参数集合放入uri;
//注:这里也支持一个键值对一个键值对地往里面放setParameter(Stringkey,Stringvalue)
uri=newURIBuilder().setScheme("http").setHost("localhost").setPort(12345)
.setPath("/doPostControllerThree").setParameters(params).build();
}catch(URISyntaxExceptione1){
e1.printStackTrace();
}
HttpPosthttpPost=newHttpPost(uri);
//HttpPosthttpPost=new
//HttpPost("http://localhost:12345/doPostControllerThree1");
//创建user参数
Useruser=newUser();
user.setName("潘晓婷");
user.setAge(18);
user.setGender("女");
user.setMotto("姿势要优雅~");
//将user对象转换为json字符串,并放入entity中
StringEntityentity=newStringEntity(JSON.toJSONString(user),"UTF-8");
//post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type","application/json;charset=utf8");
//响应模型
CloseableHttpResponseresponse=null;
try{
//由客户端执行(发送)Post请求
response=httpClient.execute(httpPost);
//从响应模型中获取响应实体
HttpEntityresponseEntity=response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if(responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+EntityUtils.toString(responseEntity));
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
//释放资源
if(httpClient!=null){
httpClient.close();
}
if(response!=null){
response.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
到此这篇关于Spring+Http请求+HttpClient实现传参的文章就介绍到这了,更多相关Spring+Http请求+HttpClient内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!