OkHttp快速入门
有时间了再详细介绍,直接上代码
一. 具体操作
1.1 具体操作
- 引入依赖 在Maven 项目中pom.xml中引入依赖
<!-- OKHttp3依赖 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.8.1</version>
</dependency>
- 封装类 OkHttpRequest.java
package com.cdmtc.remote;
import okhttp3.*;
import java.io.IOException;
public class OkHttpRequest {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
public String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
- 请求其他接口:
package com.xxl.job.core.util;
public class Test {
public static void main(String[] args) {
try {
OkHttpRequest okHttpRequest = new OkHttpRequest();
String url = "https://blog.csdn.net/qq_37128049/article/details/93890588";
String s = okHttpRequest.get(url);
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}