HTTPClient.java
2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.phxl.common.util;
import com.alibaba.fastjson.JSON;
import com.phxl.common.response.PlatFormResponse;
import com.phxl.common.response.PlatFormResponseConstant;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HTTPClient {
private static HttpClient client;
private static Logger logger=LoggerFactory.getLogger(HTTPClient.class);
//使用POST方法发送JSON数据
public static String sendJsonDataByPost(String url, String jsonData) throws Exception {
String result = "";
PlatFormResponse platFormResponse = new PlatFormResponse();
if (client == null){
client = HttpClients.createDefault();
}
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
StringEntity entity1 = new StringEntity(jsonData,"UTF-8");
post.setEntity(entity1);
logger.info("~请求地址:"+url);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
logger.info("~返回数据:"+result);
} catch (Exception e) {
platFormResponse.setFlag(PlatFormResponseConstant.ResponseBodyMsg.fail_ResultCode);
platFormResponse.setMsg(e.getMessage());
result = JSON.toJSONString(platFormResponse);
logger.error("~错误信息:"+result);
}
return result;
}
public static String sendHttpGet(String url) {
String responseContent = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "application/json");
// httpGet.addHeader("Content-Type",
// "application/json;charset=utf-8");
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getStatusLine().getStatusCode() + "\n");
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseContent);
logger.info(url + " 返回结果:" + responseContent);
response.close();
httpClient.close();
} catch (Exception e) {
logger.error("调用:" + url + " 抛出异常:",e);
}
return responseContent;
}
}