前言 HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.(官网 )
在Android通过使用OkHttp实现发送请求 因为OkHttp是开源的,所以也可以在别的Java项目中使用
引入依赖 app/build.gradle
1 2 3 4 5 6 dependencies { ... implementation 'com.squareup.okhttp3:okhttp:4.9.0' }
添加网络权限
在清单文件的<application></application>
之外添加网络权限
app/src/main/AndroidManifest.xml
1 <uses-permission android:name ="android.permission.INTERNET" />
GET请求
同步请求
<url>
:请求地址
app/src/main/java/…/MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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(); }
Android同步请求
Android发送同步请求时需要再创建一个线程才能正常运行
app/src/main/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 new Thread () { @Override public void run () { 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(); } } };
异步请求 app/src/main/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 OkHttpClient okHttpClient = new OkHttpClient ();Request request = new Request .Builder().url("<url>" ).build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback () { @Override public void onFailure (@NotNull Call call, @NotNull IOException e) { } @Override public void onResponse (@NotNull Call call, @NotNull Response response) throws IOException { if (response.isSuccessful()) { System.out.println(response.body().string()); } } });
POST请求
<key>
:参数名<value>
:参数值
同步请求 app/src/main/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 OkHttpClient okHttpClient = new OkHttpClient ();FormBody body = new FormBody .Builder().add("<key>" , "<value>" ).add("<key>" , "<value>" ).build();Request request = new Request .Builder().post(body).url("<url>" ).build();Call call = okHttpClient.newCall(request);try { Response response = call.execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); }
Android同步请求
Android发送同步请求时需要再创建一个线程才能正常运行
app/src/main/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 new Thread () { @Override public void run () { OkHttpClient okHttpClient = new OkHttpClient (); FormBody body = new FormBody .Builder().add("<key>" , "<value>" ).add("<key>" , "<value>" ).build(); Request request = new Request .Builder().post(body).url("<url>" ).build(); Call call = okHttpClient.newCall(request); try { Response response = call.execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } } };
异步请求 app/src/main/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 OkHttpClient okHttpClient = new OkHttpClient ();FormBody body = new FormBody .Builder().add("<key>" , "<value>" ).add("<key>" , "<value>" ).build();Request request = new Request .Builder().post(body).url("<url>" ).build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback () { @Override public void onFailure (@NotNull Call call, @NotNull IOException e) { } @Override public void onResponse (@NotNull Call call, @NotNull Response response) throws IOException { if (response.isSuccessful()) { System.out.println(response.body().string()); } } });
POST请求的请求体对象
传递Form表单作为参数,默认的POST请求参数类型
1 FormBody body = new FormBody .Builder().add("<key>" , "<value>" ).add("<key>" , "<value>" ).build();
<src>
:文件存放路径text/plain
:文件类型
1 2 3 4 5 6 7 8 File file1 = new File ("<src>" );File file2 = new File ("<src>" );MultipartBody body = new MultipartBody .Builder() .addFormDataPart("<key>" , file1.getName(), RequestBody.create(file1, MediaType.parse("text/plain" ))) .addFormDataPart("<key>" , file2.getName(), RequestBody.create(file2, MediaType.parse("text/plain" ))) .build();
application/json
<json>
:JSON格式的字符串
1 RequestBody body = RequestBody.create("<json>" , MediaType.parse("application/json" ));
添加请求头
<key>
:请求头键<value>
:请求头值
1 2 3 4 Request request = new Request .Builder().post(body).url("<url>" ) .addHeader("<key_1>" , "<value_1>" ) .addHeader("<key_2>" , "<value_2>" ) .build();
OkHttp的配置
创建OkHttp客户端对象时,不通过new OkHttpClient()
的方式,而是通过OkHttp.BuilderClient().bulid()
的方式,在创建对象时添加配置
不加配置 1 OkHttpClient okHttpClient = new OkHttpClient ();
配置拦截器 添加一个拦截器
既可以使用.addInterceptor()
添加拦截器,也可以使用.addNetworkInterceptor()
添加拦截器
它们的区别是:.addNetworkInterceptor()
一定在.addInterceptor()
的后面执行拦截
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 OkHttpClient okHttpClient = new OkHttpClient .Builder().addInterceptor(new Interceptor () { @NotNull @Override public Response intercept (@NotNull Chain chain) throws IOException { ... Response proceed = chain.proceed(chain.request()); ... return proceed; } }).build();
添加多个拦截器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 OkHttpClient okHttpClient = new OkHttpClient .Builder() .addInterceptor(new Interceptor () { @NotNull @Override public Response intercept (@NotNull Chain chain) throws IOException { Response proceed = chain.proceed(chain.request()); return proceed; } }) .addInterceptor(new Interceptor () { @NotNull @Override public Response intercept (@NotNull Chain chain) throws IOException { Response proceed = chain.proceed(chain.request()); return proceed; } }) .build();
拦截举例
1 2 3 4 5 6 7 8 9 10 11 12 13 OkHttpClient okHttpClient = new OkHttpClient .Builder().addInterceptor(new Interceptor () { @NotNull @Override public Response intercept (@NotNull Chain chain) throws IOException { Request request = chain.request().newBuilder().addHeader("<key>" , "<value>" ).build(); Response proceed = chain.proceed(request); return proceed; } }).build();
配置缓存
<src>
:缓存文件在本机存放路径,指定目录名1024*1024
:缓存文件最大的大小,单位字节
1 2 3 OkHttpClient okHttpClient = new OkHttpClient .Builder() .cache(new Cache (new File ("<src>" ), 1024 *1024 )) .build();
配置Cookie
先在全局声明一个变量用于存放Cookie,也可以保存到文件中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 OkHttpClient okHttpClient = new OkHttpClient .Builder() .cookieJar(new CookieJar () { @Override public void saveFromResponse (@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) { cookies = list; } @NotNull @Override public List<Cookie> loadForRequest (@NotNull HttpUrl httpUrl) { if (httpUrl.host().equals("<url>" )) { return cookies; } return null ; } }) .build();
获取响应头数据
1 2 3 4 5 6 Response response = call.execute();Headers headers = response.priorResponse().networkResponse().headers();Field namesAndValues = headers.getClass().getDeclaredField("namesAndValues" );namesAndValues.setAccessible(true ); String[] responseHeader = (String[]) namesAndValues.get(headers);
完成 参考文献 哔哩哔哩——Android架构解析 CSDN——小丫么小问号