OkHttp是用于Android和Java Application项目中的一个非常流行的Http框架。基于socket实现的Http协议。封装了异步等操作,可通过链式编程实现通讯。
1.引入框架
在gradle中
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
2.实现同步get
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GetExample {
OkHttpClient client = new OkHttpClient();//新建一个Http客户端,用于发送请求
String run(String url) throws IOException {
Request request = new Request.Builder()//基于builder模式新建请求
.url(url)//传递url 也可以加入 .get() 但默认是get请求
.build();
//newCall 是同步请求
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}
3.实现异步GET
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public final class AsynchronousGet {
private final OkHttpClient client = new OkHttpClient();//新建一个Http客户端,用于发送请求
public void run() throws Exception {
Request request = new Request.Builder()//基于builder模式新建请求
.url("http://publicobject.com/helloworld.txt")
.build();
//enqueue进入异步队列 , 参数是一个 Callback借口,从而实现回调
client.newCall(request).enqueue(new Callback() {
//传输失败执行
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
//传输成功有返回值时执行
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
//判断返回值是否成功是 2XX 开头的返回码表示成功
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//response.headers()拿到返回报文的返回头
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
//response.body()拿到返回体,string将其转换为字符串
System.out.println(responseBody.string());
}
}
});
}
public static void main(String... args) throws Exception {
new AsynchronousGet().run();
}
}
4.访问头的构造
访问头类似HashMap 之类的键对值数据结构。对于Request.Builder()主要有两个函数,一个是header(String,String);一个是addHeader(String,String);第一个会覆盖原来的值,第二个会增加进原来的值
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public final class AccessHeaders {
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println("Server: " + response.header("Server"));
System.out.println("Date: " + response.header("Date"));
System.out.println("Vary: " + response.headers("Vary"));
}
}
public static void main(String... args) throws Exception {
new AccessHeaders().run();
}
}
5.实现同步或异步POST
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public final class PostString {
//请求体的格式
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.get("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
//构建post的请求体
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * _1.0_ May 6, 2013\n"
+ " * _1.1_ June 15, 2013\n"
+ " * _1.2_ August 11, 2013\n";
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")//构建post请求的request
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))//
.build();
//newCall(request).execute()执行同步请求
//使用newCall(request).enqueue(new Callback());
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
public static void main(String... args) throws Exception {
new PostString().run();
}
}