码迷,mamicode.com
首页 > Web开发 > 详细

OkHttp

时间:2016-09-18 22:11:32      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

                                    

                                      OkHttp  

  一、简介:   OkHttp替代了HttpURLConnection。    

  二、配置依赖:   使用Android Studio   

    编辑build.gradle文件并添加依赖    compile ‘com.squareup.okhttp3:okhttp:3.4.1‘      

  三、使用  

    1.GET请求   

      OkHttpClient client = new OkHttpClient();    

       String run(String url) throws IOException {   

         Request request = new Request.Builder().url(url).build();    

         Response response = client.newCall(request).execute();      

         if (response.isSuccessful()) {            

          return response.body().string();    

        } else {            

          throw new IOException("Unexpected code " + response);    

        }  

       }  

      Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。    

      注:Response类:  

        public boolean isSuccessful() ;如果代码是在[200..300),这意味着该请求被成功接收,理解和接受,则返回true。

         response.body()返回ResponseBody类  可以方便的获取string

        当然也能获取到流的形式:   public final InputStream byteStream()     

    2.POST请求  POST提交Json数据   

      public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");   

      OkHttpClient client = new OkHttpClient();   

      String post(String url, String json) throws IOException {    

        RequestBody body = RequestBody.create(JSON, json);    

        Request request = new Request.Builder().url(url).post(body).build();   

          Response response = client.newCall(request).execute();   

         for (response.isSuccessful()) {     

          return response.body().string();    

                    } else {    

                      throw new IOException("Unexpected code " + response);   

         }  

        }  

        使用Request的post方法来提交请求体RequestBody     

    3. POST提交键值对   很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供  了很方便的方式来做这件事情。

     OkHttpClient client = new OkHttpClient();  

    string post(String url, String json) throws IOException {   

      RequestBody formBody = new FormEncodingBuilder()  .add("platform", "android").add("name", "bug") 

        .add("subject", "XXXXXXXXXXXXXXX").build();   

      Request request = new Request.Builder().url(url).post(body).build();   

      Response response = client.newCall(request).execute();  

       if (response.isSuccessful()) {    

        return response.body().string();   

      } else {    

        throw new IOException("Unexpected code " + response);   

      }  

    }   

 

  四:工具类,优化OkHttp的网络请求,处理重复部分    

   注: OkHttp不建议我们创建多个OkHttpClient,因此全局使用一个。 如果有需要,  可以使用clone方法,再进行自定义。

      enqueue为OkHttp提供的异步方法.

      import java.io.IOException;

      import java.util.List;

      import java.util.concurrent.TimeUnit;

      import org.apache.http.client.utils.URLEncodedUtils;

      import org.apache.http.message.BasicNameValuePair;

      import cn.wiz.sdk.constant.WizConstant;

      import com.squareup.okhttp3.Callback;

      import com.squareup.okhttp3.OkHttpClient;

       import com.squareup.okhttp3.Request;

      import com.squareup.okhttp3.Response;  

 

       public class OkHttpUtil {    

        private static final OkHttpClient mOkHttpClient = new OkHttpClient();    

        static{        

          mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);    

        }   

 

       /**     

       * 该不会开启异步线程。     

        */    

       public static Response execute(Request request) throws IOException{        

         return mOkHttpClient.newCall(request).execute();    

      }    

 

       /**     

       * 开启异步线程访问网络     

        */    

      public static void enqueue(Request request, Callback responseCallback){        

        mOkHttpClient.newCall(request).enqueue(responseCallback);    

      }    

 

      /**     

       * 开启异步线程访问网络, 且不在意返回结果(实现空callback)     

        */    

      public static void enqueue(Request request){        

        mOkHttpClient.newCall(request).enqueue(new Callback() {                        

          @Override            

          public void onResponse(Response arg0) throws IOException {  }                        

          @Override            

          public void onFailure(Request arg0, IOException arg1) {  }        

        });    

       }    

 

       public static String getStringFromServer(String url) throws IOException{        

         Request request = new Request.Builder().url(url).build();        

        Response response = execute(request);        

        if (response.isSuccessful()) {            

          String responseUrl = response.body().string();            

          return responseUrl;        

        } else {            

          throw new IOException("Unexpected code " + response);        

        }    

      }    

 

       private static final String CHARSET_NAME = "UTF-8";    

 

       /**     

       * 这里使用了HttpClinet的API。只是为了方便     

       */    

      public static String formatParams(List<BasicNameValuePair> params){        

        return URLEncodedUtils.format(params, CHARSET_NAME);    

      }    

 

      /**     

       * 为HttpGet 的 url 方便的添加多个name value 参数。     

       */    

      public static String attachHttpGetParams(String url, List<BasicNameValuePair> params){        

        return url + "?" + formatParams(params);    

      }    

 

       /**     

       * 为HttpGet 的 url 方便的添加1个name value 参数。 

       */    

        public static String attachHttpGetParam(String url, String name, String value){        

          return url + "?" + name + "=" + value;    

        }

      }

      高级属性其实用的不多,这里主要是对OkHttp github官方教程进行了翻译。

      同步get 下载一个文件,打印他的响应头,以string形式打印响应体。 响应体的 string() 方法对于小文档来说十分方便、

    高效。但是如果响应体太大(超过1MB),应避免适应 string()方法 ,因为他会将把整个文档加载到内存中。 对于超过1MB

    的响应body,应使用流的方式来处理body。

    private final OkHttpClient client = new OkHttpClient();  

    public void run() throws Exception {    

      Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();      

      Response response = client.newCall(request).execute();    

      if (!response.isSuccessful())

        throw new IOException("Unexpected code " + response);      

      Headers responseHeaders = response.headers();    

       for (int i = 0; i < responseHeaders.size(); i++) {      

        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));    

      }      

      System.out.println(response.body().string());

      }

      异步get 在一个工作线程中下载文件,当响应可读时回调Callback接口。读取响应时会阻塞当前线程。OkHttp

    现阶段不提供异步api来接收响应体。

    private final OkHttpClient client = new OkHttpClient();  

    public void run() throws Exception {    

      Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt").build();      

      client.newCall(request).enqueue(new Callback() {      

        @Override

        public void onFailure(Request request, Throwable throwable) {        

          throwable.printStackTrace();      

        }        

        @Override

        public void onResponse(Response response) throws IOException {        

          if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);          

            Headers responseHeaders = response.headers();        

            for (int i = 0; i < responseHeaders.size(); i++) {          

              System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));        

            }          

            System.out.println(response.body().string());      

          }    

        });

        }

       提取响应头 典型的HTTP头 像是一个 Map<String, String> :每个字段都有一个或没有值。但是一些头允许

    多个值,像Guava的Multimap。例如:HTTP响应里面提供的Vary响应头,就是多值的。OkHttp的api试图让这些

    情况都适用。 当写请求头的时候,使用header(name, value)可以设置唯一的name、value。如果已经有值,旧的

    将被移除,然后添加新的。使用addHeader(name, value)可以添加多值(添加,不移除已有的)。 当读取响应头时,

   使用header(name)返回最后出现的name、value。通常情况这也是唯一的name、value。如果没有值,那么header

    (name)将返回null。如果想读取字段对应的所有值,使用headers(name)会返回一个list。 为了获取所有的Header,

    Headers类支持按index访问。

    private final OkHttpClient client = new OkHttpClient();  

      public void run() throws Exception {    

        Request request = new Request.Builder() .url("https://api.github.com/repos/square/okhttp/issues")        

          .header("User-Agent", "OkHttp Headers.java")        

          .addHeader("Accept", "application/json; q=0.5")        

          .addHeader("Accept", "application/vnd.github.v3+json")        

          .build();      

        Response response = client.newCall(request).execute();    

          if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);      

            System.out.println("Server: " + response.header("Server"));    

             System.out.println("Date: " + response.header("Date"));    

            System.out.println("Vary: " + response.headers("Vary"));

       }

        Post方式提交String 使用HTTP POST提交请求到服务。这个例子提交了一个markdown文档到web服务,

      以HTML方式渲染markdown。因为整个请求体都在内存中,因此避免使用此api提交大文档(大于1MB)。

   \

  

OkHttp

标签:

原文地址:http://www.cnblogs.com/sangfan/p/5883147.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!