使用OkHttps发起post,get请求同步和异步基于springboot性能最佳的代码怎么写
时间: 2024-01-24 14:02:28 浏览: 28
对于使用OkHttp发起POST、GET请求的同步和异步请求,可以基于SpringBoot编写以下代码:
同步请求:
```
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
String result = response.body().string();
```
异步请求:
```
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 处理请求失败情况
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
// 处理请求成功情况
}
});
```
以上代码中,需要将`url`替换为实际请求的URL地址。对于POST请求,可以使用`POST`替换`GET`,并在请求中添加参数。此外,如果需要在SpringBoot中使用OkHttp,可以在`pom.xml`文件中添加以下依赖:
```
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.2</version>
</dependency>
```
这样就可以在SpringBoot应用中使用OkHttp发起请求了。