写一个springboot 用的 okhttp 封装工具类
时间: 2024-04-26 19:26:54 浏览: 25
好的,以下是一个简单的封装 OkHttp 的工具类:
```java
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
@Component
public class OkHttpUtils {
private OkHttpClient client = new OkHttpClient();
/**
* 发送 GET 请求
*
* @param url 请求 URL
* @return 响应结果
* @throws IOException IO 异常
*/
public String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
/**
* 发送 POST 请求
*
* @param url 请求 URL
* @param params 请求参数
* @return 响应结果
* @throws IOException IO 异常
*/
public String post(String url, Map<String, String> params) throws IOException {
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
```
使用时,只需要在 Spring Boot 应用中注入该工具类即可:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@RestController
public class TestController {
@Autowired
private OkHttpUtils okHttpUtils;
@GetMapping("/test")
public String test() throws IOException {
String url = "http://example.com";
String result = okHttpUtils.get(url);
return result;
}
@GetMapping("/testParam")
public String testParam() throws IOException {
String url = "http://example.com";
Map<String, String> params = new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");
String result = okHttpUtils.post(url, params);
return result;
}
}
```