先上代码
package post;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
public class HttpPostUtil {
private static PoolingHttpClientConnectionManager poolConnManager;
private static String BASE_URL = "http://127.0.0.1:60000";
private static int CONN_MAX_TOTAL = 200;
private static int MAX_PER_ROUTE = 200;
private static RequestConfig config;
private static CloseableHttpClient getConnection() throws Exception {
if (poolConnManager == null) {
poolConnManager = new PoolingHttpClientConnectionManager();
poolConnManager.setMaxTotal(CONN_MAX_TOTAL);
poolConnManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
}
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poolConnManager).build();
return httpClient;
}
private static RequestConfig getConfig() {
if(config == null) {
config = RequestConfig.custom().setConnectTimeout(600000) //连接超时时间
.setConnectionRequestTimeout(500000) //从线程池中获取线程超时时间
.setSocketTimeout(500000) //设置数据超时时间
.build();
}
return config;
}
/**
* @param svcName rest接口服务名称
* @param reqJSON 参数
* @return
* @throws Exception
*/
public static String postTest(String svcName,String reqJSON) throws Exception {
CloseableHttpResponse response = null;
try {
String url = BASE_URL + "/" + svcName;
HttpPost httpPost = new HttpPost(url);
StringEntity input = new StringEntity(reqJSON,"UTF-8");
input.setContentType("application/json; charset=utf-8");
httpPost.setEntity(input);
httpPost.setConfig(getConfig());
response = getConnection().execute(httpPost);
int status = response.getStatusLine().getStatusCode();
if ((status >= 200) && (status < 300)) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
}
throw new ClientProtocolException("Unexpected response status: " + status);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
response.close();
}
}
//测试方法
public static void main(String[] args) throws Exception {
String svcName = "test";
String reqest = "{\"test\"=\"123\"}";
String result = HttpPostUtil.postTest(svcName,reqest);
System.out.println(result);
}
}
支持jar包