一、pom.xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>1.3.70</version>
</dependency>
二、GET 请求
1、普通 get 请求。
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
2、添加请求头参数
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.addHeader("client_id", "123")
.addHeader("sign", "123")
.addHeader("sign_method", "123")
.addHeader("t", "123")
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
三、POST 请求
1、表单 POST 请求
OkHttpClient client = new OkHttpClient();
// 提交FormData
FormBody.Builder form = new FormBody.Builder();
form.add("name", "Tom");
form.add("age", "23");
Request request = new Request.Builder()
.url("http://httpbin.org/post")
.post(form.build())
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
2、JSON 提交
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
Map<String, Object> map = new HashMap<>();
map.put("name", "Tom");
map.put("age", 23);
Gson gson = new Gson();
String data = gson.toJson(map);
RequestBody requestBody = RequestBody.create(data, JSON);
Request request = new Request.Builder()
.url("http://httpbin.org/post")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
已在真实项目中运行。
参考 demo:
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于