package com.sinosoft.app.project.common.util;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.xmlbeans.impl.tool.XSTCTester.TestCase;
import net.sf.json.JSONObject;
import javax.net.ssl.SSLException;
public class HttpClientUtil {
// utf-8字符编码
public static final String CHARSET_UTF_8 = "utf-8";
// HTTP内容类型。
public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
// HTTP内容类型。相当于form表单的形式,提交数据
public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";
// HTTP内容类型。相当于form表单的DATA提交形式,提交数据
public static final String CONTENT_TYPE_FORM_DATA_URL = "application/json;multipart/form-data";
// HTTP内容类型。相当于form表单的形式,提交数据
public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";
public static String doPost(String url,String jsonString,String CONTENT_TYPE){
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String response = null;
try {
StringEntity sEntity = new StringEntity(jsonString,"UTF-8");
sEntity.setContentEncoding("UTF-8");
sEntity.setContentType(CONTENT_TYPE);//发送json数据需要设置contentType
post.setEntity(sEntity);
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = result;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
public static Map<String,Object> doPost1(String url,String jsonString,String CONTENT_TYPE){
Map<String,Object> map = new HashMap<String,Object>();
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String response = null;
try {
StringEntity sEntity = new StringEntity(jsonString,"UTF-8");
sEntity.setContentEncoding("UTF-8");
sEntity.setContentType(CONTENT_TYPE);//发送json数据需要设置contentType
post.setEntity(sEntity);
HttpResponse res = client.execute(post);
//map.put("statusCode", res.getStatusLine().getStatusCode());
map.put("statusCode", 404);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = result;
map.put("response", response);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return map;
}
public static String sendPost(String url,String jsonString){
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String response = null;
try {
// StringEntity sEntity = new StringEntity(jsonString);
// sEntity.setContentEncoding("UTF-8");
// sEntity.setContentType(CONTENT_TYPE);//发送json数据需要设置contentType
HttpEntity entity1 = MultipartEntityBuilder.create()
.addPart("request", new StringBody(jsonString, ContentType.APPLICATION_JSON))
.build();
post.setEntity(entity1);
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = result;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
/**
* 该http请求方法支持失败重试
* @param url 地址
* @param jsonString 请求报文
* @param CONTENT_TYPE 请求头内容
* @param recount 重试次数
* @return Map<String, String>
*/
public static Map<String, String> doPostRequest(String url,String jsonString,String CONTENT_TYPE,int recount){
Map<String, String> responseMap = new HashMap<>();
final int[] reqCount = {0};
// 请求失败重试自定义
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(
IOException exception,
int executionCount,
HttpContext context) {
if (executionCount >= recount) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectTimeoutException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
reqCount[0] = executionCount;
return true;
}
};
CloseableHttpClient client = HttpClients.custom()
.setRetryHandler(myRetryHandler)
.build();
HttpPost post = new HttpPost(url);
String response = null;
try {
StringEntity sEntity = new StringEntity(jsonString,"UTF-8");
sEntity.setContentEncoding("UTF-8");
sEntity.setContentType(CONTENT_TYPE);//发送json数据需要设置contentType
post.setEntity(sEntity);
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = result;
} else {
int statusCode = res.getStatusLine().getStatusCode();
response = "{\"code\":\"FAIL\",\"message\":\"请求短信接口失败"+ statusCode +"\"}";
}
responseMap.put("reqCount", reqCount[0]+"");
responseMap.put("response", response);
} catch (Exception e) {
responseMap.put("reqCount", reqCount[0]+"");
responseMap.put("response", "{\"code\":\"FAIL\",\"message\":\"请求发生异常,"+ e.getMessage() +"\"}");
}
return responseMap;
}
}
HttpClientUtil 工具类
最新推荐文章于 2024-11-09 12:43:52 发布