使用okhttp3写一个http请求工具类
时间: 2023-09-06 11:11:51 浏览: 58
好的,以下是一个简单的使用OkHttp3进行HTTP请求的工具类:
```java
import okhttp3.*;
import java.io.IOException;
import java.util.Map;
public class HttpUtil {
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static OkHttpClient client = new OkHttpClient();
public static String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static String get(String url, Map<String, String> headers) throws IOException {
Request.Builder builder = new Request.Builder()
.url(url);
for (Map.Entry<String, String> entry : headers.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
Request request = builder.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static String post(String url, String json, Map<String, String> headers) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request.Builder builder = new Request.Builder()
.url(url)
.post(body);
for (Map.Entry<String, String> entry : headers.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
Request request = builder.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
```
这个工具类包含了四个方法:get,post,getWithHeaders和postWithHeaders。它们可以用于发送HTTP请求并返回响应。
注意:在实际使用中,我们应该根据实际情况调整OkHttpClient的配置。例如,可以设置连接超时时间、读取超时时间、写入超时时间等。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)