效果图:
点此进入目录:[干货] 十天 教你从创意到上线APP
一、OkHttp3的基本用法
OkHttp3是Java和Android都能用,Android还有一个著名网络库叫Volley,那个只有Android能用。
导入OkHttp3
在gradle中添加依赖:
compile 'com.squareup.okhttp3:okhttp:3.4.2'
compile 'com.squareup.okhttp3:okio-1.8.0.jar'
1、发送Get请求
String url = "https://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
如果你需要在request的的header添加参数。例如Cookie,User-Agent什么的,这样:
Request request = new Request.Builder()
.url(url)
.header("键", "值")
.header("键", "值")
...
.build();
response的body有很多种输出方法,string()只是其中之一,注意是string()不是toString()。如果是下载文件就是response.body().bytes()。另外可以根据response.code()获取返回的状态码。
2、发送Post请求
String url = "https://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("键", "值")
.add("键", "值")
...
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
post请求创建request和get是一样的,只是post请求需要提交一个表单,就是RequestBody。表单的格式有好多种,普通的表单是:
RequestBody body = n