引入pom文件
XML
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
请求方法get
java
@RestController
public class WeatherController {
@GetMapping("/weather")
public String getWeather(@RequestParam("city") String city) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://*****")
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
return response.body().string();
} else {
return "Failed to get weather data";
}
} catch (IOException e) {
return "Error: " + e.getMessage();
}
}
}
post请求
java
import okhttp3.*;
import java.io.IOException;
public class Example {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
// 构造请求体
RequestBody requestBody = new FormBody.Builder()
.add("username", "admin")
.add("password", "password")
.build();
// 构造请求对象
Request request = new Request.Builder()
.url("http://example.com/api/login")
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
// 处理响应数据
System.out.println(response.body().string());
} else {
System.out.println("请求失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}