在Spring Boot中使用OkHttp可以通过封装一个工具类来实现。下面是一个简单的示例:
```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class OkHttpUtils {
private final OkHttpClient client = new OkHttpClient();
public 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();
}
}
}
```
这个工具类中,我们使用了`OkHttpClient`来发送HTTP请求,并且将其封装成了一个`get`方法,用于发送GET请求并返回响应结果。
在上面的代码中,我们使用了`@Component`注解将这个工具类声明为Spring Bean,这样就可以在其他组件中自动注入它了。例如,在一个Controller中使用这个工具类可以这样写:
```java
@RestController
public class MyController {
@Autowired
private OkHttpUtils okHttpUtils;
@GetMapping("/test")
public String test() throws IOException {
String result = okHttpUtils.get("http://example.com");
return result;
}
}
```
这样,我们就可以在Spring Boot中方便地使用OkHttp了。当然,如果需要更多的功能,还可以进一步封装这个工具类,例如支持POST请求、设置请求头等等。