一:POST
public static JSONObject post(String url, JSONObject jsonObj, String token) throws Exception {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
JSONObject result = new JSONObject();
int statusCode = 0;
String content = null;
try {
HttpPost post = new HttpPost(url);
if (null != jsonObj) {
// 构建消息实体
StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
// 参数置入
post.setEntity(entity);
}
if (null != token && !"".equals(token)) {
post.setHeader("Authorization", token);
}
CloseableHttpResponse response = closeableHttpClient.execute(post);
// 检验返回码
statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity, "utf-8");
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
result.put("code", statusCode);
result.put("content", content);
response.close();
} else {
//取出错误信息message
JSONObject jsonObject = JSON.parseObject(content);
String message = jsonObject.getJSONObject("errors").getString("message");
//logger.info("message is " + message);
result.put("code", statusCode);
result.put("content", message);
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
closeableHttpClient.close(); //关闭连接、释放资源
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
二:PUT
public static boolean put(String url, JSONObject jsonObj, String token) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
boolean returnValue = false;
HttpPut httpput = new HttpPut(url);
//设置header
httpput.setHeader("Content-type", "application/json");
if (null != token && !"".equals(token)) {
httpput.setHeader("Authorization", token);
}
//组织请求参数
StringEntity stringEntity = new StringEntity(jsonObj.toString(), "utf-8");
httpput.setEntity(stringEntity);
String content = null;
CloseableHttpResponse httpResponse = null;
try {
//响应信息
httpResponse = closeableHttpClient.execute(httpput);
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, "utf-8");
// 检验返回码
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
returnValue = true;
}
httpResponse.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
closeableHttpClient.close(); //关闭连接、释放资源
} catch (IOException e) {
e.printStackTrace();
}
return returnValue;
}