okhttp3 网络请求
时间: 2023-10-10 08:12:35 浏览: 94
OkHttp3 是一个开源的、高效的网络请求库,主要用于 Android 平台上的网络请求。它支持 HTTP/2、SPDY 和 WebSocket 协议,同时也支持同步和异步请求。下面是一个使用 OkHttp3 发起网络请求的简单示例:
1. 添加依赖
在项目的 build.gradle 文件中添加以下依赖:
```java
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
```
2. 发起 GET 请求
```java
OkHttpClient client = new OkHttpClient();
String url = "https://www.example.com/get";
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
System.out.println(responseBody);
}
```
3. 发起 POST 请求
```java
OkHttpClient client = new OkHttpClient();
String url = "https://www.example.com/post";
RequestBody requestBody = new FormBody.Builder()
.add("username", "test")
.add("password", "123456")
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
System.out.println(responseBody);
}
```
以上就是 OkHttp3 发起网络请求的简单示例,可以根据自己的实际需求进行修改和扩展。
阅读全文