import java.io.IOException;

import java.io.InputStream;

import java.nio.charset.Charset;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;

import org.apache.http.HttpEntity;

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.HttpPost;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.InputStreamEntity;

import org.apache.http.entity.StringEntity;

import org.apache.http.entity.mime.HttpMultipartMode;

import org.apache.http.entity.mime.MultipartEntityBuilder;

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.message.BasicHeader;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.protocol.HTTP;

/**

* http client 单例封装

*/

public class SingletonHttpClient {

private CloseableHttpClient httpclient;

private RequestConfig requestConfig;

private static SingletonHttpClient singleton;

/**

* 获取实例,并初始化

*/

public static SingletonHttpClient getInstance() {

if (null == singleton) {

synchronized (SingletonHttpClient.class) {

if (null == singleton) {

singleton = new SingletonHttpClient();

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

cm.setMaxTotal(1000);

singleton.httpclient = HttpClients.custom().setConnectionManager(cm)

.disableAutomaticRetries().build();

singleton.requestConfig = RequestConfig.custom()

.setConnectionRequestTimeout(10000).setSocketTimeout(10000)

.setConnectTimeout(10000).build();

return singleton;

} else {

return singleton;

}

}

} else {

return singleton;

}

}

/**

* POST 表单请求

* @param url

* @param headers

* @param params

* @return

*/

public CloseableHttpResponse post(String url, Map headers,

Map params) {

HttpPost httpPost = new HttpPost(url);

httpPost.setConfig(this.requestConfig);

if (null != headers) {

for (Map.Entry entry : headers.entrySet()) {

httpPost.addHeader(entry.getKey(), entry.getValue());

}

}

List pairs = new ArrayList();

for (Map.Entry entry : params.entrySet()) {

pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

}

try {

UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);

httpPost.setEntity(urlEncodedFormEntity);

CloseableHttpResponse response = httpclient.execute(httpPost);

return response;

} catch (Exception e) {

e.printStackTrace();

return null;

} finally {

httpPost.releaseConnection();

}

}

/**

* POST 请求体请求

* @param url

* @param headers

* @param body

* @return

*/

public CloseableHttpResponse post(String url, Map headers, String body) {

HttpPost httpPost = new HttpPost(url);

httpPost.setConfig(this.requestConfig);

if (null != headers) {

for (Map.Entry entry : headers.entrySet()) {

httpPost.addHeader(entry.getKey(), entry.getValue());

}

}

try {

httpPost.setEntity(new StringEntity(body, "UTF-8"));

CloseableHttpResponse response = httpclient.execute(httpPost);

return response;

} catch (Exception e) {

e.printStackTrace();

return null;

} finally {

httpPost.releaseConnection();

}

}

/**

* POST 单文件流(表单参数)

* @param url

* @param headers

* @param name

* @param in

* @param contentType

* @param fileName

* @return

*/

public String postFileStream(String url, Map headers, Map params,

String name, InputStream in, ContentType contentType, String fileName) {

HttpPost httpPost = new HttpPost(url);

httpPost.setConfig(this.requestConfig);

if (null != headers) {

for (Map.Entry entry : headers.entrySet()) {

httpPost.addHeader(entry.getKey(), entry.getValue());

}

}

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

// 解决文件名中文乱码

builder.setCharset(Charset.forName("utf-8"));

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

for (Map.Entry entry : params.entrySet()) {

builder.addTextBody(entry.getKey(), entry.getValue());

}

builder.addBinaryBody(name, in, contentType, fileName);

InputStream dataInstreams = null;

CloseableHttpResponse response = null;

try {

httpPost.setEntity(builder.build());

response = httpclient.execute(httpPost);

int dataStatus = -1;

if(response!=null&&response.getStatusLine()!=null)

dataStatus = response.getStatusLine().getStatusCode();

HttpEntity dataEntity = response.getEntity();

dataInstreams = dataEntity.getContent();

String resp = IOUtils.toString(dataInstreams, "UTF-8");

if(dataStatus==200){

return resp;

}else {

throw new RuntimeException("获取数据失败");

}

} catch (Exception e) {

e.printStackTrace();

return null;

} finally {

try {

in.close(); // 关闭流

httpPost.releaseConnection();

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* POST 单文件流

* @param url

* @param headers

* @param in

* @return

*/

public String postFileStream(String url, Map headers,

InputStream in) {

HttpPost httpPost = new HttpPost(url);

httpPost.setConfig(this.requestConfig);

if (null != headers) {

for (Map.Entry entry : headers.entrySet()) {

httpPost.addHeader(entry.getKey(), entry.getValue());

}

}

InputStream dataInstreams = null;

CloseableHttpResponse response = null;

try {

httpPost.setEntity(new InputStreamEntity(in));

response = httpclient.execute(httpPost);

int dataStatus = -1;

if(response!=null&&response.getStatusLine()!=null)

dataStatus = response.getStatusLine().getStatusCode();

HttpEntity dataEntity = response.getEntity();

dataInstreams = dataEntity.getContent();

String resp = IOUtils.toString(dataInstreams, "UTF-8");

if(dataStatus==200){

return resp;

}else {

throw new RuntimeException("获取数据失败");

}

} catch (Exception e) {

e.printStackTrace();

return null;

} finally {

try {

in.close(); // 关闭流

httpPost.releaseConnection();

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* POST json数据

* @param url

* @param headers

* @param jsonObject

* @return

*/

public String postjson(String url, Map headers, JSONObject jsonObject) {

HttpPost httpPost = new HttpPost(url);

httpPost.setConfig(this.requestConfig);

for (Map.Entry entry : headers.entrySet()) {

httpPost.addHeader(entry.getKey(), entry.getValue());

}

httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

StringEntity stringEntity = new StringEntity(jsonObject.toString(), "utf-8");

stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

httpPost.setEntity(stringEntity);

InputStream dataInstreams = null;

CloseableHttpResponse response = null;

try {

// System.out.println("header="+JSONObject.fromObject(headers));

response = httpclient.execute(httpPost);

int dataStatus = -1;

if(response!=null&&response.getStatusLine()!=null)

dataStatus = response.getStatusLine().getStatusCode();

HttpEntity dataEntity = response.getEntity();

dataInstreams = dataEntity.getContent();

String resp = IOUtils.toString(dataInstreams, "UTF-8");

System.out.println("resp="+resp);

if(dataStatus==200){

return resp;

}else {

throw new RuntimeException("调用机考接口失败,不能获得机考信息");

}

}catch (IOException e) {

// throw new HvnRuntimeException(e);

return null;

}finally {

IOUtils.closeQuietly(dataInstreams);

IOUtils.closeQuietly(response);

httpPost.releaseConnection();

}

}

}

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐