还在用http工具类?一行代码解决

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

以前的调用方式

最近项目上有个发起请求的需求.就开始找项目里的工具类.
发现项目里的http工具类五花八门 请求代码过长不够优雅. 具体的方法就不贴了 太占地方.
`

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
ini复制代码private static HttpsURLConnection initHttps(String url, String method,
Map<String, String> headers) throws Exception {
TrustManager[] tm = { new MyX509TrustManager() };
System.setProperty("https.protocols", "TLSv1");
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL _url = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
// 设置域名校验
http.setHostnameVerifier(new HttpUtil().new TrustAnyHostnameVerifier());
// 连接超时
http.setConnectTimeout(DEF_CONN_TIMEOUT);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(DEF_READ_TIMEOUT);
http.setUseCaches(false);
http.setRequestMethod(method);
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (null != headers && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
return http;
}
public static String get(String url, Map<String, String> params,
Map<String, String> headers) throws Exception {
HttpURLConnection http = null;
if (isHttps(url)) {
http = initHttps(initParams(url, params), _GET, headers);
} else {
http = initHttp(initParams(url, params), _GET, headers);
}
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in,
DEFAULT_CHARSET));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
in.close();
if (http != null) {
http.disconnect();// 关闭连接
}
return bufferRes.toString();
}
public static String post(String url, String params)
throws Exception {
HttpURLConnection http = null;
if (isHttps(url)) {
http = initHttps(url, _POST, null);
} else {
http = initHttp(url, _POST, null);
}
OutputStream out = http.getOutputStream();
out.write(params.getBytes(DEFAULT_CHARSET));
out.flush();
out.close();

InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in,
DEFAULT_CHARSET));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
in.close();
if (http != null) {
http.disconnect();// 关闭连接
}
return bufferRes.toString();
}

链式调用

就想着有没有方便开箱就用的请求框架…发现了一款可以链式调用的OkHttps框架很好用.

调用示例

1
2
3
4
scss复制代码List<User> users = http.sync("/users") // 请求数据的链接🔗
.get() // GET请求
.getBody() // 获取响应报文体
.toList(User.class); // 得到目标数据

快速上手

引入maven包

1
2
3
4
5
xml复制代码<dependency>
<groupId>com.ejlchina</groupId>
<artifactId>okhttps</artifactId>
<version>3.1.5</version>
</dependency>

注意:单独使用 OkHttps 需要自定义MsgConvertor,否则无法使用 自动正反序列化 相关功能.

使用

  1. 构建 HTTP
1
ini复制代码HTTP http = HTTP.builder().build();
  1. 同步请求
1
2
3
4
ini复制代码List<User> users = http.sync("/users") 
.get()
.getBody()
.toList(User.class);
  1. 异步请求
1
2
3
4
5
6
scss复制代码http.async("/users")               
.setOnResponse((HttpResult res) -> {
// 得到目标数据
User user = res.getBody().toBean(User.class);
})
.get();
  1. WebSocket
1
2
3
4
5
6
7
8
9
10
11
scss复制代码http.webSocket("/chat") 
.setOnOpen((WebSocket ws, HttpResult res) -> {
ws.send("hello world");
})
.setOnMessage((WebSocket ws,Message msg) -> {
// 从服务器接收消息(自动反序列化)
Chat chat = msg.toBean(Chat.class);
// 相同的消息发送给服务器(自动序列化 Chat 对象)
ws.send(chat);
})
.listen();

一般请求分三步:

第一步、确定请求方式

同步 HTTP(sync)、异步 HTTP(async)或 WebSocket(webSocket

第二步、构建请求任务

  • addXxxPara - 添加请求参数
  • setOnXxxx - 设置回调函数
  • tag - 添加标签

第三步、调用请求方法

HTTP 请求方法:

  • get() - GET 请求
  • post() - POST 请求
  • put() - PUT 请求
  • delete() - DELETE 请求

Websocket 方法:

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%