http請求工具-OkHttp用法


OKHttp介紹

okhttp是一個第三方類庫,用於android中請求網絡。這是一個開源項目,是安卓端最火熱的輕量級框架,由移動支付Square公司貢獻(該公司還貢獻了Picasso和LeakCanary) 。用於替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。

okhttp有自己的官網,官網網址:OKHttp官網如果想了解原碼可以在github上下載,地址是:https://github.com/square/okhttp

在AndroidStudio中使用不需要下載jar包,直接添加依賴即可: compile ‘com.squareup.okhttp3:okhttp:3.4.1’

在開發中我們會經常需要用到http請求,這里簡單介紹一個http請求工具okHttp的用法

1、導入jar包

1 <dependency>
2     <groupId>com.squareup.okhttp3</groupId>
3     <artifactId>okhttp</artifactId>
4     <version>3.9.1</version>
5 </dependency>

2、為了便於以后使用,這里封裝一個OkHttpUtil的工具類

get請求

 1 /**
 2  * get請求
 3  * @param url 請求地址
 4  * @return 請求結果
 5  */
 6 public String doGet(String url) {
 7     OkHttpClient okHttpClient = new OkHttpClient();
 8     Request request = new Request.Builder().url(url).build();
 9     Call call = okHttpClient.newCall(request);
10     try {
11         Response response = call.execute();
12         return response.body().string();
13     } catch (IOException e) {
14         e.printStackTrace();
15     }
16     return null;
17  }

post請求分為兩種,From表單形式和JSON參數形式

  • Form表單形式

 1 /**
 2  * 表單形式post請求
 3  * @param url 請求地址
 4  * @param map post請求參數
 5  * @return 請求結果
 6  */
 7 public String doPost(String url,Map<String,String> map){
 8     OkHttpClient client = new OkHttpClient();
 9     //構建一個formBody builder
10     FormBody.Builder builder = new FormBody.Builder();
11     //循環form表單,將表單內容添加到form builder中
12     for (Map.Entry<String,String> entry : map.entrySet()) {
13         String key = entry.getKey();
14         String value = entry.getValue();
15         builder.add(key,value);
16     }
17     //構建formBody,將其傳入Request請求中
18     FormBody body = builder.build();
19     Request request = new Request.Builder().url(url).post(body).build();
20     Call call = client.newCall(request);
21     //返回請求結果
22     try {
23         Response response = call.execute();
24         return response.body().string();
25     } catch (IOException e) {
26         e.printStackTrace();
27     }
28     return null;
29 }
  • JSON參數形式
 1 /**
 2  * Json body形式的post請求
 3  * @param url 請求地址
 4  * @return 請求結果
 5  */
 6 public String doPost(String url,String json){
 7     OkHttpClient client = new OkHttpClient();
 8     RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
 9     Request request = new Request.Builder()
10             .post(body)
11             .url(url).
12                     build();
13     Call call = client.newCall(request);
14     //返回請求結果
15     try {
16         Response response = call.execute();
17         return response.body().string();
18     } catch (IOException e) {
19         e.printStackTrace();
20     }
21     return null;
22 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM