关于服务端搭建和token鉴权详解:基于httpServer的web服务器简易搭建+基于jwt的token鉴权 身份验证【java/postman】
OkHttp是一个高效的HTTP客户端,它有以下默认特性:
支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
连接池减少请求延时
透明的GZIP压缩减少响应数据的大小
缓存响应内容,避免一些完全重复的请求
当网络出现问题的时候OkHttp依然坚守自己的职责,它会自动恢复一般的连接问题,如果你的服务有多个IP地址,当第一个IP请求失败时,OkHttp会交替尝试你配置的其他IP,OkHttp使用现代TLS技术(SNI, ALPN)初始化新的连接,当握手失败时会回退到TLS 1.0。
maven项目下添加依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.0</version>
</dependency>
Get请求实现:
先在postman里测试 利用wireshark进行抓包分析:
具体代码如下:
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;
public class getRequest {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "\r\n"); //get可以不加body
okhttp3.Request request = new okhttp3.Request.Builder()
.url("[你的url]")
.get()
.addHeader("Content-Type", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
//http状态码
System.out.println(response.code());
//response的头信息
System.out.println(response.headers().toString());
//请求响应时间,收到时间减去发送的时间,单位毫秒
System.out.println(response.receivedResponseAtMillis()-response.sentRequestAtMillis());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Post请求实现:
同理先在postman里测试 利用wireshark进行抓包分析
不过这块post是基于接口鉴权 传输对应的headers参数才能成功访问
直接上代码
public class postRequest implements Post {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "\r\n");
okhttp3.Request request = new okhttp3.Request.Builder()
.url("[你的url]")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("appId", "[你的id]")
.addHeader("appSecret", "[你的pwd]")
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
//http状态码
System.out.println(response.code());
//response的头信息
System.out.println(response.headers().toString());
//请求响应时间,收到时间减去发送的时间,单位毫秒
System.out.println(response.receivedResponseAtMillis() - response.sentRequestAtMillis());
} catch (IOException e) {
e.printStackTrace();
}
}
执行结果: