java okhttp3 工具类
时间: 2023-08-16 09:05:04 浏览: 126
我封装的okhttp.zip_MHZ_OKhttp封装_okhttp_okhttp3_okhttp3 封装
下面是一个简单的 Java OkHttp3 工具类的示例代码:
```java
import okhttp3.*;
import java.io.IOException;
import java.util.Map;
public class OkHttpUtil {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
/**
* GET 请求
*
* @param url 请求地址
* @return 响应结果字符串
* @throws IOException 请求失败抛出异常
*/
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();
}
}
/**
* POST 请求
*
* @param url 请求地址
* @param params 请求参数
* @return 响应结果字符串
* @throws IOException 请求失败抛出异常
*/
public static String post(String url, Map<String, String> params) throws IOException {
FormBody.Builder formBuilder = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
formBuilder.add(entry.getKey(), entry.getValue());
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
/**
* POST 请求,请求体为 JSON 格式
*
* @param url 请求地址
* @param json 请求体 JSON 字符串
* @return 响应结果字符串
* @throws IOException 请求失败抛出异常
*/
public static String postJson(String url, String json) throws IOException {
RequestBody requestBody = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) throws IOException {
// GET 请求
System.out.println(OkHttpUtil.get("https://www.baidu.com"));
// POST 请求,表单参数
Map<String, String> params = new HashMap<>();
params.put("name", "张三");
params.put("age", "18");
System.out.println(OkHttpUtil.post("http://localhost:8080/user", params));
// POST 请求,JSON 参数
String json = "{\"name\":\"张三\",\"age\":18}";
System.out.println(OkHttpUtil.postJson("http://localhost:8080/user", json));
}
}
```
阅读全文