java后台开发经常会需要发送HTTP请求,经常会使用Apache的HttpClient发送请求。
maven项目需要在pom.xml文件引入
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.1version>
dependency>
1.设置请求参数
List<BasicNameValuePair> content = new ArrayList<BasicNameValuePair>();
content.add(new BasicNameValuePair("tradingPartner", "jaden");
content.add(new BasicNameValuePair("documentProtocol", "jaden"));
content.add(new BasicNameValuePair("requestMessage", sw.toString()));
//调用Http请求方法
String result = sentHttpPostRequest(url, content);
2.发送HTTP请求
public String sentHttpPostRequest(String url, List<BasicNameValuePair> content) throws Exception {
//构建HttpClient实例
CloseableHttpClient httpclient = HttpClients.createDefault();
//设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectTimeout(60000)
.setConnectionRequestTimeout(60000)
.build();
//指定POST请求
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
//包装请求体
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.addAll(content);
HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");
//发送请求
httppost.setEntity(request);
CloseableHttpResponse httpResponse = httpclient.execute(httppost);
//读取响应
HttpEntity entity = httpResponse.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
return result;
}
说明:
1.显式设置发送编码格式为UTF-8,且接收信息编码格式也为UTF-8; (不设置容易产生中文乱码)
1.创建可关闭的HttpClient,即 CloseableHttpClient httpclient;
2.读取响应,也是用可关闭的response,即CloseableHttpResponse httpResponse;
好处:这样可以使得创建出来的HTTP实体,可以被Java虚拟机回收掉,不至于出现一直占用资源的情况。
3.后端接收请求参数
这种key-value请求方式,
1>后端可以使用request.getParameter(key);获得对应的value值;
2>如果使用流的方式获取,也是可以得到信息的,eg:tradingPartner=jaden&documentProtocol=jaden。
大部分同上述代码相同,不同之处在于包装请求体部分:
1.发送HTTP请求
String jsonStr = {
"name":"jaden",
"age":"23",
"other":"xxx"
};
HttpEntity param = new StringEntity(jsonStr, "UTF-8");
//设置请求体
httppost.setEntity(param);
说明:
1.这里也对字符串请求参数,显式设置编码格式为UTF-8; (不设置容易产生中文乱码)
2.后端接收请求参数
这种请求参数为字符串请求方式,
1>后端可以使用request.getParameter(key);无法获取到任何值;
2>如果使用流的方式获取,也是可以得到对应发送的流信息。
扩充:获取request中流信息代码如下:
注意:这里也显式设置编码为UTF-8
public String getReqeustData(HttpServletRequest request) {
String data = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
if (StringUtils.isEmpty(data)) {
return null;
}
} catch (Exception e) {
logger.error("read Inputstream for httpReqeust error", e);
}
return data;
}
使用HttpGet即可
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet request = new HttpGet(url);
request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) ...");
CloseableHttpResponse response = httpclient.execute(request);
// read response
日常总结,助人助己。