OKHttp的各种情况使用

概念:

Android 提供了两种HTTP通信方式:一种是Java原生的Apache的HTTP通信:HttpClient ,另一种是android所使用的HttpURLConnection。

作为较为成熟的HTTP通信机制OKHTTP正在取代上述两种HTTP通信方式,在android 4.4版本后,Volley也剔除了HttpURLConnection,改为使用OKHTTP进行通信。它的优势在于更稳定,可以设置多个IP地址进行失败连接问题的处理等等。在进行HTTPS访问时也更加稳定和安全。

下面是OKHTTP的简单应用。主要来自于GitHub:https://github.com/square/okhttp/wiki


OKHTTP支持所有的HTTP请求方式:GET,POST,HEAD.....这里主要是进行GET与POST为例进行介绍。

OKHTTP有两种请求方式:

同步方式:

execute

异步方式:

enqueue

使用方式:

为一下所有函数定义全局变量:

  1. private final OkHttpClient client = new OkHttpClient();  

GET请求:

使用get请求下载文件,返回的是String。

  1. public void run() throws Exception {  
  2.        Request request = new Request.Builder()  
  3.                .url("http://publicobject.com/helloworld.txt")  
  4.                .build();  
  5.   
  6.        client.newCall(request).enqueue(new Callback() {  
  7.            @Override  
  8.            public void onFailure(Call call, IOException e) {  
  9.   
  10.            }  
  11.   
  12.            @Override  
  13.            public void onResponse(Call call, Response response) throws IOException {  
  14.                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
  15.   
  16.                Headers responseHeaders = response.headers();  
  17.                for (int i = 0, size = responseHeaders.size(); i < size; i++) {  
  18.                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));  
  19.                }  
  20.   
  21.                System.out.println(response.body().string());  
  22.            }  
  23.        });  
  24.    }  

使用Get请求JSON数据:

  1. static class Gist {  
  2.     Map<String, GistFile> files;  
  3. }  
  4.   
  5. static class GistFile {  
  6.     String content;  
  7. }  
  8.   
  9. private final Gson gson = new Gson();  
  10.   
  11. public void run_JSON() throws Exception {  
  12.     Request request = new Request.Builder()  
  13.             .url("https://api.github.com/gists/c2a7c39532239ff261be")  
  14.             .build();  
  15.     client.newCall(request).enqueue(new Callback() {  
  16.         @Override  
  17.         public void onFailure(Call call, IOException e) {  
  18.   
  19.         }  
  20.   
  21.         @Override  
  22.         public void onResponse(Call call, Response response) throws IOException {  
  23.   
  24.             if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
  25.   
  26.             Gist gist = gson.fromJson(response.body().charStream(), Gist.class);  
  27.             for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {  
  28.                 System.out.println("11111111111111111111 "+entry.getKey());  
  29.                 System.out.println(entry.getValue().content);  
  30.             }  
  31.         }  
  32.     });  
  33.   
  34. }  

POST请求:

使用POST发送一个String型数据:

  1. public static final MediaType MEDIA_TYPE_MARKDOWN  
  2.            = MediaType.parse("text/x-markdown; charset=utf-8"); //content-type  
  3.    /** 
  4.     * 发送一个string型数据 
  5.     * @throws Exception 
  6.     */  
  7.    public void run_string() throws Exception {  
  8.        String postBody = ""  
  9.                + "Releases\n"  
  10.                + "--------\n"  
  11.                + "\n"  
  12.                + " * _1.0_ May 6, 2013\n"  
  13.                + " * _1.1_ June 15, 2013\n"  
  14.                + " * _1.2_ August 11, 2013\n";  
  15.   
  16.        Request request = new Request.Builder()  
  17.                .url("https://api.github.com/markdown/raw")  
  18.                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))  
  19.                .build();  
  20.   
  21.        client.newCall(request).enqueue(new Callback() {  
  22.            @Override  
  23.            public void onFailure(Call call, IOException e) {  
  24.   
  25.            }  
  26.   
  27.            @Override  
  28.            public void onResponse(Call call, Response response) throws IOException {  
  29.                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
  30.   
  31.                System.out.println(response.body().string());  
  32.   
  33.            }  
  34.        });  
  35.   
  36.    }  

使用POST请求发送一个键值对:

  1. /** 
  2.  * 发送一个post键值对参数 
  3.  * @throws Exception 
  4.  */  
  5. public void run_keyValue() throws Exception {  
  6.     RequestBody formBody = new FormBody.Builder()  
  7.             .add("search""Jurassic Park")  
  8.             .build();  
  9.     Request request = new Request.Builder()  
  10.             .url("https://en.wikipedia.org/w/index.php")  
  11.             .post(formBody)  
  12.             .build();  
  13.   
  14.     client.newCall(request).enqueue(new Callback() {  
  15.         @Override  
  16.         public void onFailure(Call call, IOException e) {  
  17.         }  
  18.   
  19.         @Override  
  20.         public void onResponse(Call call, Response response) throws IOException {  
  21.             if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
  22.   
  23.             System.out.println(response.body().string());  
  24.         }  
  25.     });  
  26.   
  27. }  


使用POST发送一个数据流:

  1. /** 
  2.     * //发送一个流 
  3.     * @throws Exception 
  4.     */  
  5.    public void run_Streaming() throws Exception {  
  6.        RequestBody requestBody = new RequestBody() {  
  7.   
  8.            @Override public MediaType contentType() {  
  9.                return MEDIA_TYPE_MARKDOWN;  
  10.            }  
  11.   
  12.            @Override public void writeTo(BufferedSink sink) throws IOException {  
  13.                sink.writeUtf8("Numbers\n");  
  14.                sink.writeUtf8("-------\n");  
  15.                for (int i = 2; i <= 997; i++) {  
  16.                    sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));  
  17.                }  
  18.            }  
  19.   
  20.            private String factor(int n) {  
  21.                for (int i = 2; i < n; i++) {  
  22.                    int x = n / i;  
  23.                    if (x * i == n) return factor(x) + " × " + i;  
  24.                }  
  25.                return Integer.toString(n);  
  26.            }  
  27.        };  
  28.   
  29.        Request request = new Request.Builder()  
  30.                .url("https://api.github.com/markdown/raw")  
  31.                .post(requestBody)  
  32.                .build();  
  33.   
  34.        client.newCall(request).enqueue(new Callback() {  
  35.            @Override  
  36.            public void onFailure(Call call, IOException e) {  
  37.   
  38.   
  39.            }  
  40.   
  41.            @Override  
  42.            public void onResponse(Call call, Response response) throws IOException {  
  43.                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
  44.                System.out.println(response.body().string());  
  45.            }  
  46.        });  
  47.   
  48.   
  49.    } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值