第一种
此版本为基本的版本,可实现接口调用,发送数据,接受接口响应数据,请求方式为post
/**
*date 传递的json数据
*port 接口地址
*return 返回的json数据
*/
public static JSONObject doPost(JSONObject date, String port) {
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = port;
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
StringEntity s = new StringEntity(date.toString(), "utf-8");//此处为解决传输来的数据变成乱码的问题
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.addHeader("content-type", "text/xml;charset:utf-8");
post.setEntity(s);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//此处判断状态是否为200
String result = EntityUtils.toString(res.getEntity());
jsonObject = JSONObject.parseObject(result);// 返回json格式:
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}
同样此版本为基本的版本,可实现接口调用,发送数据,接受接口响应数据,请求方式为get
public static JSONObject doGet(JSONObject date, String port) {
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = port;
HttpGet get = new HttpGet(url);
JSONObject jsonObject = null;
try {
StringEntity s = new StringEntity(date.toString(), "utf-8");//此处为解决传输来的数据变成乱码的问题
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.addHeader("content-type", "text/xml;charset:utf-8");
post.setEntity(s);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//此处判断状态是否为200
String result = EntityUtils.toString(res.getEntity());
jsonObject = JSONObject.parseObject(result);// 返回json格式:
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}
第二种
在第一种的基础上添加请求失败异常信息收集,请求失败重试
/**
*date 传递的json数据
*port 接口地址
*return 返回的json数据
*/
public static String doPost(String json, String url) {
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(url);
//设置请求参数的格式为json
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
//设置请求的参数
httpPost.setEntity(new StringEntity(json, ContentType.create("text/json", "UTF-8")));
CloseableHttpClient client = HttpClients.createDefault();
//发送请求,保存消息
for (int index = 0; index <= RETRY_MAX_TIME; index++) {
try {
response = client.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
} catch (Exception e) {
//发送失败或者超时,重试
++index;
if ((RETRY_MAX_TIME + 1) != index) {
LOGGER.error(String.format("HttpHostConnectException:...... retry time = %d phonenNum : %s", index, json));
} else {
LOGGER.error("post fail over threeTimes " + json);
}
continue;
} finally {
try {
if (response != null)
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return "";
}
同样的,如果想修改为get请求,将 HttpPost httpPost = new HttpPost(url);修改为 HttpGet get = new HttpGet(url)即可,博主在这里就不再代码编辑