帮我封装个okhttp工具类
时间: 2023-07-29 15:14:13 浏览: 61
当然,我可以帮你封装一个简单的OkHttp工具类。以下是一个示例代码,你可以根据自己的需求进行修改和扩展:
```java
import okhttp3.*;
import java.io.IOException;
import java.util.Map;
public class OkHttpUtils {
private static OkHttpClient client;
private static OkHttpClient getClient() {
if (client == null) {
client = new OkHttpClient();
}
return client;
}
public static String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = getClient().newCall(request).execute()) {
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
}
public static String post(String url, Map<String, String> params) throws IOException {
FormBody.Builder formBodyBuilder = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
formBodyBuilder.add(entry.getKey(), entry.getValue());
}
RequestBody requestBody = formBodyBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = getClient().newCall(request).execute()) {
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
}
}
```
这个工具类封装了get和post方法,可以发送HTTP请求并返回响应结果。你可以使用`OkHttpUtils.get(url)`发送GET请求,或者使用`OkHttpUtils.post(url, params)`发送POST请求。其中,url是请求的URL,params是POST请求的参数。
请注意,这只是一个简单的封装示例,你可以根据自己的项目需求进行扩展和优化。例如,可以添加超时设置、请求头配置等功能。