2019-10-30 20:18:19
只記錄使用方法,只記錄使用方法,只記錄使用方法。
okhttp3是一個能在java和安卓上使用的網絡請求框架
一丶導入
.maven導入方式
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.2.2</version> </dependency>
.gradle引入方式
compile 'com.squareup.okhttp3:okhttp:4.2.2'
.jar包導入
-鏈接:https://pan.baidu.com/s/1BFMcd0ntRTzjhbrBEcis_g 提取碼:74fb
二丶get請求
package com.lxl.learn.okhttp3; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Learn_Okhttp3 { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); Request req = new Request.Builder().url("https://www.baidu.com/").build(); Response rep = client.newCall(req).execute(); System.out.println("返回碼:"+rep.code()); //rep.header("這里寫頭,可以得到相關值") //rep.body().string() 只能被調用一次,在要對返回內容做多次操作時用字符串存一下 System.out.println("返回內容:"+rep.body().string()); } }
1.添加請求頭參數
package com.lxl.learn.okhttp3; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Learn_Okhttp3 { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); Request req = new Request.Builder() .url("https://www.baidu.com/") .addHeader("鍵", "值") .addHeader("鍵", "值") //....... .build(); //異步請求 client.newCall(req).enqueue(new Callback() { @Override public void onResponse(Call arg0, Response arg1) throws IOException { //請求成功會執行 System.out.println("返回碼:"+arg1.code()); System.out.println(arg1.body().string()); } @Override public void onFailure(Call arg0, IOException arg1) { //請求失敗或網絡錯誤會執行這里 System.out.println("請求失敗"); } }); } }
三丶POST請求
package com.lxl.learn.okhttp3; import okhttp3.Call; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class Learn_Okhttp3 { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); RequestBody body = new FormBody.Builder() .add("鍵", "值") //例如 .add("user","123456") // .add("passwd","abc1234") .build(); Request req = new Request.Builder() .url("https://www.baidu.com/") .addHeader("鍵", "值") //header方法是覆蓋,addHeader才是添加 .addHeader("鍵", "值") .post(body) .build(); //同步請求 Call call = client.newCall(req); Response response = call.execute(); System.out.println("返回碼:"+response.code()); System.out.println(response.body().toString()); } }
RequestBody 一般用於普通表單提交
其中提交數據不只是有普通表單,有時是json,有時是數據文件,這時就必須寫上RequestBody的數據格式,一般常見的三種:
- application/x-www-form-urlencoded 數據是個普通表單
- multipart/form-data 數據里有文件
- application/json 數據是json
普通表單數據格式可以省略:因為FormBody繼承了RequestBody,它已經指定了數據類型為application/x-www-form-urlencoded。
1.json數據提交
package com.lxl.learn.okhttp3; import org.json.simple.JSONObject; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class Learn_Okhttp3 { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); JSONObject json = new JSONObject(); json.put("user", "123456"); RequestBody body = RequestBody.create(JSON,json.toJSONString()); Request req = new Request.Builder() .url("https://www.baidu.com/") .post(body) .build(); //同步請求 Call call = client.newCall(req); Response response = call.execute(); System.out.println("返回碼:"+response.code()); System.out.println(response.body().toString()); } }
2.數據文件提交
package com.lxl.learn.okhttp3; import java.io.File; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class Learn_Okhttp3 { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); File file = new File("e:\\a.jpg"); //MultipartBody也是繼承了RequestBody /*源碼可知它適用於這五種Content-Type: * * public static final MediaType MIXED = MediaType.parse("multipart/mixed"); * public static final MediaType ALTERNATIVE = MediaType.parse("multipart/alternative"); * public static final MediaType DIGEST = MediaType.parse("multipart/digest"); * public static final MediaType PARALLEL = MediaType.parse("multipart/parallel"); * public static final MediaType FORM = MediaType.parse("multipart/form-data"); * */ RequestBody body = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file)) .build(); Request req = new Request.Builder() .url("https://www.baidu.com/") .post(body) .build(); //同步請求 Call call = client.newCall(req); Response response = call.execute(); System.out.println("返回碼:"+response.code()); System.out.println(response.body().toString()); } }
3.使用異步請求
在android中一般都是使用異步的處理,OkHttpClient.newCall(Request req).enqueue(Callback call),但是在異步請求后不能直接修改ui控件,android中不允許后台線程修改ui,只允許主線程修改
4.下載文件
package com.lxl.learn.okhttp3; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Learn_Okhttp3 { public static void main(String[] args) throws Exception { String url = "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg"; Request request = new Request.Builder().url(url).build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onResponse(Call arg0, Response arg1) throws IOException { System.out.println("大小:"+arg1.body().contentLength()/1024+"kb"); InputStream is = arg1.body().byteStream(); byte[] buf = new byte[2048]; File file = new File("E:\\a.jpg"); if(file.exists()) file.createNewFile(); FileOutputStream fo = new FileOutputStream(file); int len = 0; while((len = is.read(buf)) != -1) { fo.write(buf,0,len); } fo.flush(); if(is != null) is.close(); if(fo != null) fo.close(); System.out.println("下載完成"); } @Override public void onFailure(Call arg0, IOException arg1) { } }); } }
暫時記這點,有時間詳細看看源碼。