在服务器发送HTTP请求

Posted by 石玉军 on 2018-07-26

使用之前首先添加maven依赖或者是jar包

1
2
3
4
5
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>

下面给出工具类代码,一个简单发送Get和Post请求的例子

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
78
79
80
81
82
83
84
85
public class HttpUtils {

/*
*发送简单post请求
*/
public static JSONObject post(String url) {
HttpPost post = new HttpPost(url);
return getResult(post);
}
/*
*发送带Header的post请求
*/
public static JSONObject post(String url, Map<String, String> map) {
HttpPost post = new HttpPost(url);
if (!map.isEmpty()) {
Set<Map.Entry<String, String>> entrys = map.entrySet();
for (Map.Entry<String, String> entry : entrys) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
return getResult(post);
}
/*
*发送带Header的get请求
*/
public static JSONObject get(String url, Map<String, String> map) {
HttpGet get = new HttpGet(url);
if (!map.isEmpty()) {
Set<Map.Entry<String, String>> entrys = map.entrySet();
for (Map.Entry<String, String> entry : entrys) {
get.setHeader(entry.getKey(), entry.getValue());
}
}
return getResult(get);

}
/*
*发送简单的get请求
*/
public static JSONObject get(String url) {
HttpGet get = new HttpGet(url);
return getResult(get);

}
/*
*发送请求方法,请求响应为JSONObject
*/
private static JSONObject getResult(HttpRequestBase requestBase) {
CloseableHttpClient httpClient = HttpClients.createDefault();

String result = null;
try {
result = EntityUtils.toString(httpClient.execute(requestBase).getEntity());
httpClient.close();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
return new JSONObject(JSON.parseObject(result));
}
}
/*
*当请求响应为String时
*/
public static String getString(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
String result = null;
try {
result = EntityUtils.toString(httpClient.execute(get).getEntity());
httpClient.close();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
return result;
}
}
}

`