导入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
创建一个HttpClienUtil类
public class HttpClientUtil {
private static Log logger = LogFactory.getLog("imp");
public static String get(String url) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
// setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect
// Manager获取Connection
// 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。
// 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(15000).setConnectionRequestTimeout(15000).setSocketTimeout(15000)
.build();
httpGet.setConfig(defaultRequestConfig);
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态
logger.info("http GET response.getStatusLine() " + response.getStatusLine());
if (entity != null) {
logger.info("rsponse content length " + entity.getContentLength());
return EntityUtils.toString(entity, "utf-8");
}
} finally {
response.close();
}
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String get(Map<String, String> header, String url) throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
if (header != null) {
for (Entry<String, String> param : header.entrySet()) {
httpGet.addHeader(param.getKey(), param.getValue());
}
}
// setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect
// Manager获取Connection
// 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。
// 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000)
.build();
httpGet.setConfig(defaultRequestConfig);
logger.info("executing request " + httpGet.getURI());
// 执行get请求.
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态
logger.info("http GET with Header response.getStatusLine() " + response.getStatusLine());
if (entity != null) {
logger.info("http GET with Header response content length " + entity.getContentLength());
return EntityUtils.toString(entity, "utf-8");
}
} finally {
response.close();
}
} finally {
// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String post(Map<String, String> header, Map<String, String> reqParam, String url) throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
if (header != null) {
for (Entry<String, String> param : header.entrySet()) {
httpPost.addHeader(param.getKey(), param.getValue());
}
}
// setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect
// Manager获取Connection
// 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。
// 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000)
.build();
httpPost.setConfig(defaultRequestConfig);
logger.info("executing request " + httpPost.getURI());
// 装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (reqParam != null) {
for (Entry<String, String> entry : reqParam.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "utf-8");
httpPost.setEntity(reqEntity);
// 执行post请求.
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
// 状态为正常时,进行body内容获取
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
logger.info("http post response result " + result);
return result;
}
} else {
logger.info("http post response.getStatusLine() " + response.getStatusLine());
String result = status.getReasonPhrase();
return result;
}
} finally {
response.close();
}
} finally {
// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String post(Map<String, String> header, List<Map<String, String>> reqParamList, String url) throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
if (header != null) {
for (Entry<String, String> param : header.entrySet()) {
httpPost.addHeader(param.getKey(), param.getValue());
}
}
// setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect
// Manager获取Connection
// 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。
// 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000)
.build();
httpPost.setConfig(defaultRequestConfig);
logger.info("executing request " + httpPost.getURI());
// 装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map<String,String> reqParam : reqParamList) {
if (reqParam != null) {
for (Entry<String, String> entry : reqParam.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
}
UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "utf-8");
httpPost.setEntity(reqEntity);
// 执行post请求.
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
// 状态为正常时,进行body内容获取
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
logger.info("http post response result " + result);
return result;
}
} else {
logger.info("http post response.getStatusLine() " + response.getStatusLine());
String result = status.getReasonPhrase();
return result;
}
} finally {
response.close();
}
} finally {
// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static byte[] getBytes(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet(url);
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000)
.build();
httpget.setConfig(defaultRequestConfig);
CloseableHttpResponse response = httpClient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态
logger.info("http GET with Header response.getStatusLine() " + response.getStatusLine());
if (entity != null) {
logger.info("http GET with Header response content length " + entity.getContentLength());
return EntityUtils.toByteArray(entity);
}
} finally {
response.close();
}
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String postFileMultiPart(String url, Map<String, ContentBody> reqParam) throws ClientProtocolException, IOException {
return postFileMultiPart(null, url, reqParam);
}
public static String postFileMultiPart(Map<String, String> header, String url, Map<String, ContentBody> reqParam) throws ClientProtocolException,
IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
if (header != null) {
for (Entry<String, String> param : header.entrySet()) {
httpPost.addHeader(param.getKey(), param.getValue());
}
}
logger.info("post file httpPostUrl=" + httpPost.getURI());
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000)
.build();
httpPost.setConfig(defaultRequestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// 这里一定要设置编码,否则文件名传递会出现乱码
multipartEntityBuilder.setCharset(Charset.forName("utf-8"));
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (Entry<String, ContentBody> param : reqParam.entrySet()) {
multipartEntityBuilder.addPart(param.getKey(), param.getValue());
}
HttpEntity reqEntity = multipartEntityBuilder.build();
httpPost.setEntity(reqEntity);
// 执行post请求
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
// 状态为正常时,进行body内容获取
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
logger.info("http post file response result " + result);
return result;
}
} else {
logger.info("http post file response.getStatusLine() " + response.getStatusLine());
String result = status.getReasonPhrase();
return result;
}
} finally {
response.close();
}
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String post(String url, Map<String, String> reqParam) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
// setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect
// Manager获取Connection
// 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。
// 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000)
.build();
httpPost.setConfig(defaultRequestConfig);
logger.info("post httpPostUrl=" + httpPost.getURI());
// 装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (reqParam != null) {
for (Entry<String, String> entry : reqParam.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "utf-8");
httpPost.setEntity(reqEntity);
// 执行post请求.
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
// 状态为正常时,进行body内容获取
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
logger.info("http post response result " + result);
return result;
}
} else {
logger.info("http post response.getStatusLine() " + response.getStatusLine());
String result = status.getReasonPhrase();
return result;
}
} finally {
response.close();
}
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static JSONObject post4cookie(String url, JSONObject reqParam) throws ClientProtocolException, IOException {
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
try {
HttpPost httpPost = new HttpPost(url);
// setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect
// Manager获取Connection
// 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。
// 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000)
.build();
httpPost.setConfig(defaultRequestConfig);
// 装填参数
StringEntity reqEntity = new StringEntity(reqParam.toString(), Charset.forName("UTF-8"));
reqEntity.setContentType("application/json");
httpPost.setEntity(reqEntity);
// 执行post请求.
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
logger.info("Response content length: " + entity.getContentLength());
// 打印响应内容
JSONObject res = new JSONObject();
String httpRes = EntityUtils.toString(entity, Charset.forName("UTF-8"));
res.put("httpRes", httpRes);
JSONObject cookie = new JSONObject();
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
cookie.put(cookies.get(i).getName(), cookies.get(i).getValue());
}
res.put("cookie", cookie);
return res;
}
} finally {
response.close();
}
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 以body为json串的形式提交数据
*
* @param url
* @param json
* @return
* @throws IOException
*/
public static String postBody(String url, String json) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(50000).setConnectionRequestTimeout(50000).setSocketTimeout(120000)
.build();
httpPost.setConfig(defaultRequestConfig);
httpPost.setEntity(new StringEntity(json, "utf-8"));
httpPost.setHeader("Content-Type", "application/json");
// 执行post请求.
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
logger.info("http post body json response result " + result);
return result;
}
} else {
logger.info("http post body json response.getStatusLine() " + response.getStatusLine());
String result = status.getReasonPhrase();
return result;
}
} finally {
response.close();
}
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
整合HttpClienUtil类
public class HttpClientUtil {
/**
* 错误返回空字符串
*/
public static final String EMPTY_STR="";
/**
* 连接超时时间 毫秒
*/
public static final Integer ConnectTimeout = 2000;
/**
* 得到config对象
* @return
*/
public static RequestConfig getRequestConfig(){
// setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect
// Manager获取Connection
// 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。
// 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(ConnectTimeout).setConnectionRequestTimeout(ConnectTimeout)
.setSocketTimeout(ConnectTimeout).build();
return defaultRequestConfig;
}
/**
* httpGet.setConfig
* @param httpGet
*/
public static void setHttpGetConfig(HttpGet httpGet){
if(httpGet!=null){
httpGet.setConfig(getRequestConfig());
}
}
/**
* setHttpGetHeader
* @param httpGet
*/
public static void setHttpGetHeader(HttpGet httpGet,Map<String, String> paramMap){
if(httpGet!=null){
setHttpGetConfig(httpGet);
if (paramMap != null) {
for (Map.Entry<String, String> param : paramMap.entrySet()) {
httpGet.addHeader(param.getKey(), param.getValue());
}
}
}
}
/**
* HttpPost.setConfig
* @param
*/
public static void setHttpPostConfig(HttpPost httpPost){
if(httpPost!=null){
httpPost.setConfig(getRequestConfig());
}
}
/**
* setHttpPostHeader
* @param
*/
public static void setHttpPostHeader(HttpPost httpPost,Map<String, String> paramMap){
if(httpPost!=null){
setHttpPostConfig(httpPost);
if ( paramMap != null) {
for (Map.Entry<String, String> param : paramMap.entrySet()) {
httpPost.addHeader(param.getKey(), param.getValue());
}
}
}
}
/**
* setHttpPostBody
*/
public static void setHttpPostBody(HttpPost httpPost,Map<String, String> bodyParamMap) throws UnsupportedEncodingException {
if (httpPost !=null && bodyParamMap != null) {
// 装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : bodyParamMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "utf-8");
httpPost.setEntity(reqEntity);
}
}
/**
*closeHttpClient
*CloseableHttpResponse
*/
public static void close(CloseableHttpClient httpClient,CloseableHttpResponse response){
closeHttpClient(httpClient);
closeableHttpResponse(response);
}
/**
* closeHttpClient
*/
public static void closeHttpClient(CloseableHttpClient httpClient){
try {
if(httpClient!=null){
httpClient.close();
}
} catch (IOException e) {
log.error("httpClient关闭异常");
}
}
/**
* CloseableHttpResponse
* @param response
*/
public static void closeableHttpResponse(CloseableHttpResponse response){
try {
if(response!=null){
response.close();
}
} catch (IOException e) {
log.error("CloseableHttpResponse关闭异常");
}
}
/**
* 得到请求的访问参数
* @param entity
* @param status
* @throws IOException
*/
public static String getStrByHttpEntity(StatusLine status,HttpEntity entity) throws IOException {
if (status.getStatusCode() == HttpStatus.SC_OK) {
if (entity != null) {
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
log.info(entity.getContentLength()+"getStrByHttpEntity response result: " + result);
return result;
}
return EMPTY_STR;
} else {
log.info("status.getStatusCode(): " + status.getStatusCode());
return status.getReasonPhrase();
}
}
//************************************************************************调用方法
/**
* 简单的get请求
* @param url
* @return
* @throws Exception
*/
public static String get(String url) throws Exception {
return get(url,null);
}
/**
* 简单的get请求+请求参数
* @param paramMap
* @param url
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws ParseException
*/
public static String get(String url,Map<String, String> paramMap) throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
HttpGet httpGet = null;
try {
httpGet = new HttpGet(url);
setHttpGetHeader(httpGet,paramMap);
log.info("paramMap get executing " + httpGet.getURI());
// 执行post请求.
response = httpClient.execute(httpGet);
// 获取响应实体
return getStrByHttpEntity(response.getStatusLine(),response.getEntity());
}catch (Exception e){
log.error("get:"+e.getMessage());
e.printStackTrace();
}finally {
close(httpClient,response);
}
return EMPTY_STR;
}
/**
*
* @param paramHeaderMap 请求头参数
* @param bodyParamMap body参数
* @param url
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws ParseException
*/
public static String post(Map<String, String> paramHeaderMap, Map<String, String> bodyParamMap, String url) throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
HttpPost httpPost = null;
try {
httpPost = new HttpPost(url);
setHttpPostHeader(httpPost,paramHeaderMap);
setHttpPostBody(httpPost,bodyParamMap);
log.info("paramHeaderMap bodyParamMap post executing " + httpPost.getURI());
// 执行post请求.
response = httpClient.execute(httpPost);
return getStrByHttpEntity(response.getStatusLine(),response.getEntity());
}catch (Exception e){
log.error("post:"+e.getMessage());
e.printStackTrace();
}finally {
// 关闭连接,释放资源
close(httpClient,response);
}
return EMPTY_STR;
}
/**
*
* @param paramHeaderMap 请求头参数
* @param bodyParamList body参数
* @param url
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws ParseException
*/
public static String post(Map<String, String> paramHeaderMap, List<Map<String, String>> bodyParamList, String url) throws ClientProtocolException, IOException, ParseException {
Map<String, String> bodyParamMap=null;
if(bodyParamList!=null){
bodyParamMap=new HashMap<>();
for (Map<String, String> map :bodyParamList) {
bodyParamMap.putAll(map);
}
}
return post(paramHeaderMap,bodyParamMap,url);
}
/**
* 通过get请求得到byte[]
* @param url
* @return
* @throws Exception
*/
public static byte[] getByteByGet(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
HttpGet httpGet = null;
try {
httpGet = new HttpGet(url);
setHttpGetConfig(httpGet);
log.info(" getByteByGet executing " + httpGet.getURI());
// 执行post请求.
response = httpClient.execute(httpGet);
// 获取响应实体
HttpEntity entity = response.getEntity();
StatusLine status = response.getStatusLine();
// 打印响应状态
log.info("getByteByGetwith Header response.getStatusLine() " + response.getStatusLine());
if (status.getStatusCode() == HttpStatus.SC_OK) {
if (entity != null) {
return EntityUtils.toByteArray(entity);
}
}
}catch (Exception e){
log.error("getByteByGet:"+e.getMessage());
e.printStackTrace();
}finally {
closeHttpClient(httpClient);
closeableHttpResponse(response);
}
return new byte[0];
}
/**
* 文件上传
* @param url
* @param bodyParamMap
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String postFileMultiPart(String url, Map<String, ContentBody> bodyParamMap)
throws ClientProtocolException, IOException {
return postFileMultiPart(null, url, bodyParamMap);
}
/**
* 文件上传
* @param paramHeaderMap
* @param url
* @param bodyParamMap
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String postFileMultiPart(Map<String, String> paramHeaderMap, String url,
Map<String, ContentBody> bodyParamMap)throws ClientProtocolException,IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
HttpPost httpPost=null;
try {
httpPost = new HttpPost(url);
setHttpPostHeader(httpPost,paramHeaderMap);
setHttpPostConfig(httpPost);
log.info("postFileMultiPart post file httpPostUrl=" + httpPost.getURI());
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// 这里一定要设置编码,否则文件名传递会出现乱码
multipartEntityBuilder.setCharset(Charset.forName("utf-8"));
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (Map.Entry<String, ContentBody> param : bodyParamMap.entrySet()) {
multipartEntityBuilder.addPart(param.getKey(), param.getValue());
}
HttpEntity reqEntity = multipartEntityBuilder.build();
httpPost.setEntity(reqEntity);
// 执行post请求
response = httpClient.execute(httpPost);
return getStrByHttpEntity(response.getStatusLine(),response.getEntity());
}catch (Exception e){
log.error("postFileMultiPart:"+e.getMessage());
e.printStackTrace();
}finally {
closeHttpClient(httpClient);
closeableHttpResponse(response);
}
return EMPTY_STR;
}
/**
*
* @param url
* @param reqParam JSONObject
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static JSONObject post4cookie(String url, JSONObject jsonParam) throws ClientProtocolException, IOException {
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
CloseableHttpResponse response=null;
// 打印响应内容
JSONObject returnJson = new JSONObject();
try {
HttpPost httpPost = new HttpPost(url);
setHttpPostConfig(httpPost);
// 装填参数
StringEntity reqEntity = new StringEntity(jsonParam.toString(), Charset.forName("UTF-8"));
reqEntity.setContentType("application/json");
httpPost.setEntity(reqEntity);
// 执行post请求.
response = httpClient.execute(httpPost);
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
log.info("Response content length: " + entity.getContentLength());
String httpRes = EntityUtils.toString(entity, Charset.forName("UTF-8"));
returnJson.put("httpRes", httpRes);
JSONObject cookie = new JSONObject();
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
cookie.put(cookies.get(i).getName(), cookies.get(i).getValue());
}
returnJson.put("cookie", cookie);
return returnJson;
}
}catch (Exception e){
log.error("post4cookie:"+e.getMessage());
e.printStackTrace();
}finally {
close(httpClient,response);
}
return returnJson;
}
/**
* 以body为json串的形式提交数据
*
* @param url
* @param json
* @return
* @throws IOException
*/
public static String postBody(String url, String json) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
try {
HttpPost httpPost = new HttpPost(url);
setHttpPostConfig(httpPost);
httpPost.setEntity(new StringEntity(json, "utf-8"));
httpPost.setHeader("Content-Type", "application/json");
// 执行post请求.
response = httpClient.execute(httpPost);
return getStrByHttpEntity(response.getStatusLine(),response.getEntity());
}catch (Exception e){
log.error("postBody:"+e.getMessage());
e.printStackTrace();
} finally {
close(httpClient,response);
}
return EMPTY_STR;
}
}
测试
public static void main(String[] args) throws Exception{
String s = HttpClientUtil.get("https://kunpeng.csdn.net/ad/template/1330?positionId=56&queryWord=");
System.out.println(s);
}