引子:
OkHttp是當下比較流行的網絡請求框架之一。易用性,復用性都比較好。一般使用時,最好再對它進行再次封裝,以符合具體場景的使用需求。本文主要介紹大概的使用方法。
庫的引用:
引入okhttp的庫,而且okhttp依賴okio的庫,所以兩者必須同步引入。
方式1)下載jar包,然后放到工程里(3.3.0是版本號,可以更換的)
okhttp-3.3.0.jar
okio-1.8.0.jar
方式2)Maven依賴(3.3.0是版本號,可以更換的)
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.0</version>
</dependency>
方式3)androidStudio中,直接添加gradle引用;(3.10.0是okhttp庫版本號)
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okio:okio:1.8.0'
}
okhttp的同步請求以及異步請求的寫法 :
網絡請求都有同步異步之分,okhttp也不例外,在okhttp中,兩者區別如下:
同步請求會阻塞線程,並且不能運行在UI線程;
異步請求不會阻塞,也可以運行在UI線程,但是必須編寫一個Callback;
/** * 同步請求 */
private void testSyncOkHttp() throws IOException { OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build(); Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); Response response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } /** * 異步請求 */
private void testAsyncOkHttp() { OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build(); Request request = new Request.Builder().url("http://www.publicobject.com/helloworld.txt").get().build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(tag, "onFailure;" + e.getLocalizedMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d(tag, "onResponse;" + response.body().string()); } }); }
Get請求和Post請求(都以同步請求為例)
Get
private void testGetSync() { 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鍵值對,調用如下代碼. header方法可以重復調用
Request request = new Request.Builder() .header("鍵","值") .header("鍵","值") .header("鍵","值") ... .url(url) .build();
Post:
可以看到post請求就是將 鍵值對放在了FormBody中,然后調用Request.Builder()的post方法設置進去.
private void testPostSync() { 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方式只是其中一種。因為post的表單格式有多種。
常見的3種格式為:
1)application/x-www-form-urlencoded 數據是個普通表單,鍵值對形式(這種格式,直接使用上面的代碼就可以)
2)multipart/form-data 數據里有文件
3) application/json 數據是個json
格式2)的RequestBody構建方式為:
RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file)) .build();
格式3)的requestBody構建方式為:
MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, "你的json");
以上內容只做備忘或者入門者閱讀,有更多更復雜的情況,可根據上面的線索自行百度谷歌。