1.引入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
2.具体使用
2.1 get请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.get() //默认为GET请求,可以不写
.addHeader("param", param)
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
if (response.body()!=null) {
String string = response.body().string();
if (StringUtils.isNotEmpty(string)) {
JSONObject jsonObject = JSONObject.parseObject(string);
String message = jsonObject.getString("message");
}
}
} catch (IOException e) {
e.printStackTrace();
}
2.2 post请求
OkHttpClient client = new OkHttpClient();
//指定当前请求的 contentType 为 json 数据
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String jsonStr = "{\n" +
" \"name\": \"name\",\n" +
" \"age\": {\n" +
" \"age\": \"1\"\n" +
" }\n" +
"}";
Request request = new Request.Builder()
.url(url)
.addHeader("param", param)
.post(RequestBody.create(JSON, jsonStr))
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
if (response.body()!=null) {
String string = response.body().string();
if (StringUtils.isNotEmpty(string)) {
JSONObject jsonObject = JSONObject.parseObject(string);
String message = jsonObject.getString("message");
}
}
} catch (IOException e) {
e.printStackTrace();
}
本文详细介绍了如何使用OkHttp库进行HTTP请求,包括GET和POST两种方式。在GET请求中,我们创建OkHttpClient实例,构建Request对象并执行。在POST请求中,我们设置了请求体为JSON格式,并发送数据。这两个示例都捕获了可能的IOException并处理。
6万+

被折叠的 条评论
为什么被折叠?



