最近在做http访问第三方接口获取数据,整理一下整合配置。
1.导入依赖jar包。
个人使用的是SSM框架spring版本4.2.2,再次基础上导入jar包。
2.新建资源文件:httpclient.properties
http.request.connectionRequestTimeout=500
http.request.connectTimeout=5000
http.request.socketTimeout=30000
http.request.staleConnectionCheckEnabled=true
http.pool.maxTotal=200
http.pool.defaultMaxPerRoute=100
http.maxIdleTime=1
3.新建http配置文件:spring-httpclient.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 定义httpclient连接池 -->
<bean id="httpClientConnectionManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" destroy-method="close">
<!-- 设置连接总数 -->
<property name="maxTotal" value="${http.pool.maxTotal}"></property>
<!-- 设置每个地址的并发数 -->
<property name="defaultMaxPerRoute" value="${http.pool.defaultMaxPerRoute}"></property>
</bean>
<!-- 定义 HttpClient工厂,这里使用HttpClientBuilder构建-->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
<property name="connectionManager" ref="httpClientConnectionManager"></property>
</bean>
<!-- 得到httpClient的实例 -->
<bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build"/>
<!-- 定期清理无效的连接 -->
<bean class="com.energy.ims.util.HttpClient.ClearConnectionsHandler" destroy-method="shutdown">
<constructor-arg index="0" ref="httpClientConnectionManager"/>
</bean>
<!-- 定义requestConfig的工厂 -->
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
<!-- 从连接池中获取到连接的最长时间 -->
<property name="connectionRequestTimeout" value="${http.request.connectionRequestTimeout}"/>
<!-- 创建连接的最长时间 -->
<property name="connectTimeout" value="${http.request.connectTimeout}"/>
<!-- 数据传输的最长时间 -->
<property name="socketTimeout" value="${http.request.socketTimeout}"/>
<!-- 提交请求前测试连接是否可用 -->
<property name="staleConnectionCheckEnabled" value="${http.request.staleConnectionCheckEnabled}"/>
</bean>
<!-- 得到requestConfig实例 -->
<bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" />
</beans>
3.将spring-httpclient.xml文件引入,spring.xml配置中
注意1:配置注解扫描,及扫描路径。
注意2:引入资源文件,路径不得错误。
4.封装代码
1.httpclient响应实体,可以拓展
package com.ssm.common.http;
import java.io.Serializable;
/**
* HttpClient响应实体
* @autho 董杨炀
* @time 2017年5月8日 下午3:35:26
*/
public class HttpResult implements Serializable{
private static final long serialVersionUID = 1L;
/**
* 状体码
*/
private Integer statusCode;
/**
* 响应内容
*/
private String content;
public HttpResult(){
}
public HttpResult(Integer statusCode, String content) {
this.statusCode = statusCode;
this.content = content;
}
/**
* 获取状体码
* @return 状体码
*/
public Integer getStatusCode() {
return statusCode;
}
/**
* 设置状体码
* @param statusCode 状体码
*/
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
/**
* 获取响应内容
* @return 响应内容
*/
public String getContent() {
return content;
}
/**
* 设置响应内容
* @param content 响应内容
*/
public void setContent(String content) {
this.content = content;
}
/**
* @autho 董杨炀
* @time 2017年5月8日 下午3:37:23
* @return
*/
@Override
public String toString() {
return "HttpResult [statusCode=" + statusCode + ", content=" + content + "]";
}
}
2.定义暴露出来的httpClient操作对象.此对象实现spring的BeanFactoryAware接口.(通过注解生成实例)
package com.ssm.common.http;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ssm.utils.StringUtils;
/**
* @autho 董杨炀
* @time 2017年5月8日 下午3:22:09
*/
@Component("httpClientOperate")
public class HttpClientOperate implements BeanFactoryAware{
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
/**
* 将required设置为false:
* 为了避免RequestConfig没被注进来的时候其他方法都不能用,报createbeanfailedexception
*
*/
@Autowired(required=false)
private RequestConfig requestConfig;
private CloseableHttpClient getHttpClient(){
return this.beanFactory.getBean(CloseableHttpClient.class);
}
/**
* 无参get请求
* @autho 董杨炀
* @time 2017年5月8日 下午3:30:08
* @param url
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String doGet(String url) throws ClientProtocolException, IOException{
// 创建http GET请求
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);//设置请求参数
CloseableHttpResponse response = null;
try {
// 执行请求
response = this.getHttpClient().execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
return content;
}
} finally {
if (response != null) {
response.close();
}
//httpclient.close();
}
return null;
}
/**
* 有参get请求
* @param url
* @return
* @throws URISyntaxException
* @throws IOException
* @throws ClientProtocolException
*/
public String doGet(String url , Map<String, String> params) throws URISyntaxException, ClientProtocolException, IOException{
URIBuilder uriBuilder = new URIBuilder(url);
if(params != null){
for(String key : params.keySet()){
uriBuilder.setParameter(key, params.get(key));
}
}
return this.doGet(uriBuilder.build().toString());
}
/**
* 有参post请求
* @autho 董杨炀
* @time 2017年5月8日 下午3:32:48
* @param url
* @param params
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public HttpResult doPost(String url , Map<String, String> params) throws ClientProtocolException, IOException{
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if(params != null){
// 设置2个post参数,一个是scope、一个是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
for(String key : params.keySet()){
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
}
CloseableHttpResponse response = null;
try {
// 执行请求
response = this.getHttpClient().execute(httpPost);
// 判断返回状态是否为200
/*if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}*/
return new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(), "UTF-8"));
} finally {
if (response != null) {
response.close();
}
//httpclient.close();
}
}
/**
* 有参post请求,json交互
* @autho 董杨炀
* @time 2017年5月8日 下午3:33:01
* @param url
* @param json
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public HttpResult doPostJson(String url , String json) throws ClientProtocolException, IOException{
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if(StringUtils.isNotBlank(json)){
//标识出传递的参数是 application/json
StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
}
CloseableHttpResponse response = null;
try {
// 执行请求
response = this.getHttpClient().execute(httpPost);
// 判断返回状态是否为200
/*if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}*/
return new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(), "UTF-8"));
} finally {
if (response != null) {
response.close();
}
//httpclient.close();
}
}
/**
* 无参post请求
* @autho 董杨炀
* @time 2017年5月8日 下午3:33:27
* @param url
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public HttpResult doPost(String url) throws ClientProtocolException, IOException{
return this.doPost(url, null);
}
}
3.自定义类,利用线程定时扫描清理无效连接
package com.ssm.common.http;
import org.apache.http.conn.HttpClientConnectionManager;
/**
* 自定义定时清理无效链接(httpclient)
* @autho 董杨炀
* @time 2017年5月8日 下午3:16:59
*/
public class ClearConnectionsHandler extends Thread{
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public ClearConnectionsHandler(HttpClientConnectionManager connMgr) {
this.connMgr = connMgr;
this.start();
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// 关闭失效的连接
connMgr.closeExpiredConnections();
}
}
} catch (InterruptedException ex) {
// 结束
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
4.用到的StringUtils工具类
package com.ssm.common.Tool;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 字符串操作工具类
* @author dongyangyang
* @Date 2016/12/28 23:12
* @Version 1.0
*
*/
public class StringUtils {
/**
* 首字母变小写
* @param str
* @return
*/
public static String firstCharToLowerCase(String str) {
char firstChar = str.charAt(0);
if (firstChar >= 'A' && firstChar <= 'Z') {
char[] arr = str.toCharArray();
arr[0] += ('a' - 'A');
return new String(arr);
}
return str;
}
/**
* 首字母变大写
* @param str
* @return
*/
public static String firstCharToUpperCase(String str) {
char firstChar = str.charAt(0);
if (firstChar >= 'a' && firstChar <= 'z') {
char[] arr = str.toCharArray();
arr[0] -= ('a' - 'A');
return new String(arr);
}
return str;
}
/**
* 判断是否为空
* @param str
* @return
*/
public static boolean isEmpty(final String str) {
return (str == null) || (str.length() == 0);
}
/**
* 判断是否不为空
* @param str
* @return
*/
public static boolean isNotEmpty(final String str) {
return !isEmpty(str);
}
/**
* 判断是否空白
* @param str
* @return
*/
public static boolean isBlank(final String str) {
int strLen;
if ((str == null) || ((strLen = str.length()) == 0))
return true;
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 判断是否不是空白
* @param str
* @return
*/
public static boolean isNotBlank(final String str) {
return !isBlank(str);
}
/**
* 判断多个字符串全部是否为空
* @param strings
* @return
*/
public static boolean isAllEmpty(String... strings) {
if (strings == null) {
return true;
}
for (String str : strings) {
if (isNotEmpty(str)) {
return false;
}
}
return true;
}
/**
* 判断多个字符串其中任意一个是否为空
* @param strings
* @return
*/
public static boolean isHasEmpty(String... strings) {
if (strings == null) {
return true;
}
for (String str : strings) {
if (isEmpty(str)) {
return true;
}
}
return false;
}
/**
* checkValue为 null 或者为 "" 时返回 defaultValue
* @param checkValue
* @param defaultValue
* @return
*/
public static String isEmpty(String checkValue, String defaultValue) {
return isEmpty(checkValue) ? defaultValue : checkValue;
}
/**
* 字符串不为 null 而且不为 "" 并且等于other
* @param str
* @param other
* @return
*/
public static boolean isNotEmptyAndEquelsOther(String str, String other) {
if (isEmpty(str)) {
return false;
}
return str.equals(other);
}
/**
* 字符串不为 null 而且不为 "" 并且不等于other
* @param str
* @param other
* @return
*/
public static boolean isNotEmptyAndNotEquelsOther(String str, String... other) {
if (isEmpty(str)) {
return false;
}
for (int i = 0; i < other.length; i++) {
if (str.equals(other[i])) {
return false;
}
}
return true;
}
/**
* 字符串不等于other
* @param str
* @param other
* @return
*/
public static boolean isNotEquelsOther(String str, String... other) {
for (int i = 0; i < other.length; i++) {
if (other[i].equals(str)) {
return false;
}
}
return true;
}
/**
* 判断字符串不为空
* @param strings
* @return
*/
public static boolean isNotEmpty(String... strings) {
if (strings == null) {
return false;
}
for (String str : strings) {
if (str == null || "".equals(str.trim())) {
return false;
}
}
return true;
}
/**
* 比较字符相等
* @param value
* @param equals
* @return
*/
public static boolean equals(String value, String equals) {
if (isAllEmpty(value, equals)) {
return true;
}
return value.equals(equals);
}
/**
* 比较字符串不相等
* @param value
* @param equals
* @return
*/
public static boolean isNotEquals(String value, String equals) {
return !equals(value, equals);
}
public static String[] split(String content, String separatorChars) {
return splitWorker(content, separatorChars, -1, false);
}
public static String[] split(String str, String separatorChars, int max) {
return splitWorker(str, separatorChars, max, false);
}
public static final String[] EMPTY_STRING_ARRAY = new String[0];
private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) {
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return EMPTY_STRING_ARRAY;
}
List<String> list = new ArrayList<String>();
int sizePlus1 = 1;
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
if (separatorChars == null) {
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else if (separatorChars.length() == 1) {
char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else {
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
}
if (match || (preserveAllTokens && lastMatch)) {
list.add(str.substring(start, i));
}
return (String[]) list.toArray(EMPTY_STRING_ARRAY);
}
/**
* 消除转义字符
* @param str
* @return
*/
public static String escapeXML(String str) {
if (str == null)
return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
switch (c) {
case '\u00FF':
case '\u0024':
break;
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '\"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
if (c >= '\u0000' && c <= '\u001F')
break;
if (c >= '\uE000' && c <= '\uF8FF')
break;
if (c >= '\uFFF0' && c <= '\uFFFF')
break;
sb.append(c);
break;
}
}
return sb.toString();
}
/**
* 将字符串中特定模式的字符转换成map中对应的值
*
* @param s
* 需要转换的字符串
* @param map
* 转换所需的键值对集合
* @return 转换后的字符串
*/
public static String replace(String s, Map<String, Object> map) {
StringBuilder ret = new StringBuilder((int) (s.length() * 1.5));
int cursor = 0;
for (int start, end; (start = s.indexOf("${", cursor)) != -1 && (end = s.indexOf("}", start)) != -1;) {
ret.append(s.substring(cursor, start)).append(map.get(s.substring(start + 2, end)));
cursor = end + 1;
}
ret.append(s.substring(cursor, s.length()));
return ret.toString();
}
public static String replace(String s, Object... objs) {
if (objs == null || objs.length == 0)
return s;
if (s.indexOf("{}") == -1)
return s;
StringBuilder ret = new StringBuilder((int) (s.length() * 1.5));
int cursor = 0;
int index = 0;
for (int start; (start = s.indexOf("{}", cursor)) != -1;) {
ret.append(s.substring(cursor, start));
if (index < objs.length)
ret.append(objs[index]);
else
ret.append("{}");
cursor = start + 2;
index++;
}
ret.append(s.substring(cursor, s.length()));
return ret.toString();
}
/**
* 字符串格式化工具,参数必须以{0}之类的样式标示出来.大括号中的数字从0开始。
*
* @param source
* 源字符串
* @param params
* 需要替换的参数列表,写入时会调用每个参数的toString().
* @return 替换完成的字符串。如果原始字符串为空或者参数为空那么将直接返回原始字符串。
*/
public static String replaceArgs(String source, Object... params) {
if (params == null || params.length == 0 || source == null || source.isEmpty()) {
return source;
}
StringBuilder buff = new StringBuilder(source);
StringBuilder temp = new StringBuilder();
int startIndex = 0;
int endIndex = 0;
String param = null;
for (int count = 0; count < params.length; count++) {
if (params[count] == null) {
param = null;
} else {
param = params[count].toString();
}
temp.delete(0, temp.length());
temp.append("{");
temp.append(count);
temp.append("}");
while (true) {
startIndex = buff.indexOf(temp.toString(), endIndex);
if (startIndex == -1) {
break;
}
endIndex = startIndex + temp.length();
buff.replace(startIndex, endIndex, param == null ? "" : param);
}
startIndex = 0;
endIndex = 0;
}
return buff.toString();
}
public static String substringBefore(final String s, final String separator) {
if (isEmpty(s) || separator == null) {
return s;
}
if (separator.isEmpty()) {
return "";
}
final int pos = s.indexOf(separator);
if (pos < 0) {
return s;
}
return s.substring(0, pos);
}
public static String substringBetween(final String str, final String open, final String close) {
if (str == null || open == null || close == null) {
return null;
}
final int start = str.indexOf(open);
if (start != -1) {
final int end = str.indexOf(close, start + open.length());
if (end != -1) {
return str.substring(start + open.length(), end);
}
}
return null;
}
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return "";
}
final int pos = str.indexOf(separator);
if (pos == -1) {
return "";
}
return str.substring(pos + separator.length());
}
/**
* 转换为字节数组
* @param str
* @return
*/
public static String toString(byte[] bytes){
try {
return new String(bytes, "utf-8");
} catch (UnsupportedEncodingException e) {
return null;
}
}
/**
* 转换为字节数组
* @param str
* @return
*/
public static byte[] getBytes(String str){
if (str != null){
try {
return str.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
return null;
}
}else{
return null;
}
}
public static void main(String[] a){
String escapeXML = escapeXML("\\");
System.out.println(escapeXML);
}
}
客户端访问测试
1.直接启动ssm工程war测试,写一个bean实现InitializingBean接口,重写afterPropertiesSet()方法.
InitializingBean接口作用:在bean初始化完成之后自动执行afterPropertiesSet()方法
@Component:当IOC容器扫描到此注解标记的class就会装载该bean
package com.ssm.common.http;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
/**
* @autho 董杨炀
* @time 2017年5月8日 下午4:25:54
*/
@Component
public class MyHttpTest implements InitializingBean{
@Resource
private HttpClientOperate httpClientOperate;
/**
* @autho 董杨炀
* @time 2017年5月8日 下午4:26:20
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
//无参get请求
String result = httpClientOperate.doGet("http://www.baidu.com");
System.out.println(result);
//有参get请求
Map<String,String> map = new HashMap<>();
map.put("waybillNo", "12341223");
String result2 = httpClientOperate.doGet("http://www.baidu.com", map);
System.out.println(result2);
//post请求
HttpResult entity = httpClientOperate.doPost("http://10.230.21.133:8180/esb2/rs/ESB_FOSS2ESB_FOSS_THE_RECEIVING_VERIFY");
System.out.println(entity);
//有参post请求
HttpResult entity2 = httpClientOperate.doPost("http://10.230.21.133:8180/esb2/rs/ESB_FOSS2ESB_FOSS_THE_RECEIVING_VERIFY", map);
System.out.println(entity2);
//有参post请求rest服务 JSON
String json = "{\"waybillNo\":\"12341223\"}";
HttpResult entity3 = httpClientOperate.doPostJson("http://10.230.21.133:8180/esb2/rs/ESB_FOSS2ESB_FOSS_THE_RECEIVING_VERIFY",json);
System.out.println(entity3);
}
}
2.如果你没有去git检出改ssm项目.利用junit测试也可以.或者手动main启动spring容器加载配置来测试
package com.ssm.httptest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ssm.common.http.HttpClientOperate;
import com.ssm.common.http.HttpResult;
/**
* 手动启动spring容器测试
* @autho 董杨炀
* @time 2017年5月8日 下午3:55:10
*/
public class HttpClientTest {
public static void main(String[] args) throws IOException, URISyntaxException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "spring-test.xml" });
HttpClientOperate httpClientOperate = (HttpClientOperate)context.getBean("httpClientOperate");
//无参get请求
String result = httpClientOperate.doGet("http://www.baidu.com");
System.out.println(result);
//有参get请求
Map<String,String> map = new HashMap<>();
map.put("waybillNo", "12341223");
String result2 = httpClientOperate.doGet("http://www.baidu.com", map);
System.out.println(result2);
//post请求
HttpResult entity = httpClientOperate.doPost("http://10.230.21.133:8180/esb2/rs/ESB_FOSS2ESB_FOSS_THE_RECEIVING_VERIFY");
System.out.println(entity);
//有参post请求
HttpResult entity2 = httpClientOperate.doPost("http://10.230.21.133:8180/esb2/rs/ESB_FOSS2ESB_FOSS_THE_RECEIVING_VERIFY", map);
System.out.println(entity2);
//有参post请求rest服务 JSON
String json = "{\"waybillNo\":\"12341223\"}";
HttpResult entity3 = httpClientOperate.doPostJson("http://10.230.21.133:8180/esb2/rs/ESB_FOSS2ESB_FOSS_THE_RECEIVING_VERIFY",json);
System.out.println(entity3);
}
}
spring-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 引入httpclient -->
<import resource="spring-httpclient.xml"/>
<!-- 配置注解扫描器 -->
<context:component-scan base-package="com.ssm.common.http"/>
<!-- 加载资源文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 配置资源文件 -->
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:httpclient.properties</value>
</list>
</property>
</bean>
<!-- 配置连接池,数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${driver}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="user" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
</beans>
对于请求复杂,可再进行封装
设置请求头