okhttp3.0

来源:互联网 发布:云计算管理系统 编辑:程序博客网 时间:2024/06/07 00:13

1.使用前准备

Android Studio 配置gradle:

compile 'com.squareup.okhttp3:okhttp:3.2.0'  compile 'com.squareup.okio:okio:1.7.0'

添加网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

2.同步get

/** * 同步Get方法 */private void okHttp_synchronousGet() {    new Thread(new Runnable() {        @Override        public void run() {            try {                String url = "https://api.github.com/";                OkHttpClient client = new OkHttpClient();                Request request = new Request.Builder().url(url).build();                okhttp3.Response response = client.newCall(request).execute();                if (response.isSuccessful()) {                    Log.i(TAG, response.body().string());                } else {                    Log.i(TAG, "okHttp is request error");                }            } catch (IOException e) {                e.printStackTrace();            }        }    }).start();}

3.异步get

/** * 异步 Get方法 */private void okHttp_asynchronousGet(){    try {        Log.i(TAG,"main thread id is "+Thread.currentThread().getId());        String url = "https://api.github.com/";        OkHttpClient client = new OkHttpClient();        Request request = new Request.Builder().url(url).build();        client.newCall(request).enqueue(new okhttp3.Callback() {            @Override            public void onFailure(okhttp3.Call call, IOException e) {            }            @Override            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {                // 注:该回调是子线程,非主线程                Log.i(TAG,"callback thread id is "+Thread.currentThread().getId());                Log.i(TAG,response.body().string());            }        });    } catch (Exception e) {        e.printStackTrace();    }}

添加请求头:

okhttp3添加请求头,需要在Request.Builder()使用.header(String key,String value)或者.addHeader(String key,String value);
使用.header(String key,String value),如果key已经存在,将会移除该key对应的value,然后将新value添加进来,即替换掉原来的value;
使用.addHeader(String key,String value),即使当前的可以已经存在值了,只会添加新value的值,并不会移除/替换原来的值。

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"));  }


4.post:(键值对)

private void okHttp_postFromParameters() {    new Thread(new Runnable() {        @Override        public void run() {            try {                // 请求完整url:http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json                String url = "http://api.k780.com:88/";                OkHttpClient okHttpClient = new OkHttpClient();                String json = "{'app':'weather.future','weaid':'1','appkey':'10003'," +                        "'sign':'b59bc3ef6191eb9f747dd4e83c99f2a4','format':'json'}";                RequestBody formBody = new FormBody.Builder().add("app", "weather.future")                        .add("weaid", "1").add("appkey", "10003").add("sign",                                "b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")                        .build();                Request request = new Request.Builder().url(url).post(formBody).build();                okhttp3.Response response = okHttpClient.newCall(request).execute();                Log.i(TAG, response.body().string());            } catch (Exception e) {                e.printStackTrace();            }        }    }).start();}


5.post(string):

public static final MediaType MEDIA_TYPE_MARKDOWN      = MediaType.parse("text/x-markdown; charset=utf-8");  private final OkHttpClient client = new OkHttpClient();  public void run() throws Exception {    String postBody = ""        + "Releases\n"        + "--------\n"        + "\n"        + " * _1.0_ May 6, 2013\n"        + " * _1.1_ June 15, 2013\n"        + " * _1.2_ August 11, 2013\n";    Request request = new Request.Builder()        .url("https://api.github.com/markdown/raw")        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))        .build();    Response response = client.newCall(request).execute();    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);    System.out.println(response.body().string());  }


6.post(streaming):

public static final MediaType MEDIA_TYPE_MARKDOWN      = MediaType.parse("text/x-markdown; charset=utf-8");  private final OkHttpClient client = new OkHttpClient();  public void run() throws Exception {    RequestBody requestBody = new RequestBody() {      @Override public MediaType contentType() {        return MEDIA_TYPE_MARKDOWN;      }      @Override public void writeTo(BufferedSink sink) throws IOException {        sink.writeUtf8("Numbers\n");        sink.writeUtf8("-------\n");        for (int i = 2; i <= 997; i++) {          sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));        }      }      private String factor(int n) {        for (int i = 2; i < n; i++) {          int x = n / i;          if (x * i == n) return factor(x) + " × " + i;        }        return Integer.toString(n);      }    }; Request request = new Request.Builder()        .url("https://api.github.com/markdown/raw")        .post(requestBody)        .build();    Response response = client.newCall(request).execute();    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);    System.out.println(response.body().string());  }


7.post(file):

public static final MediaType MEDIA_TYPE_MARKDOWN      = MediaType.parse("text/x-markdown; charset=utf-8");  private final OkHttpClient client = new OkHttpClient();  public void run() throws Exception {    File file = new File("README.md");    Request request = new Request.Builder()        .url("https://api.github.com/markdown/raw")        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))        .build();    Response response = client.newCall(request).execute();    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);    System.out.println(response.body().string());  }

8.responese(gson)
private final OkHttpClient client = new OkHttpClient();  private final Gson gson = new Gson();  public void run() throws Exception {    Request request = new Request.Builder()        .url("https://api.github.com/gists/c2a7c39532239ff261be")        .build();    Response response = client.newCall(request).execute();    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);    Gist gist = gson.fromJson(response.body().charStream(), Gist.class);    for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {      System.out.println(entry.getKey());      System.out.println(entry.getValue().content);    }  }  static class Gist {    Map<String, GistFile> files;  }  static class GistFile {    String content;  }
............................................................................................

一.异步上传文件

上传文件本身也是一个POST请求,上一篇没有讲,这里我们补上。首先定义上传文件类型:

public static final MediaType MEDIA_TYPE_MARKDOWN            = MediaType.parse("text/x-markdown; charset=utf-8");

将sdcard根目录的wangshu.txt文件上传到服务器上:

private void postAsynFile() {        mOkHttpClient=new OkHttpClient();        File file = new File("/sdcard/wangshu.txt");        Request request = new Request.Builder()                .url("https://api.github.com/markdown/raw")                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))                .build();            mOkHttpClient.newCall(request).enqueue(new Callback() {                @Override                public void onFailure(Call call, IOException e) {                }                @Override                public void onResponse(Call call, Response response) throws IOException {                    Log.i("wangshu",response.body().string());                }            });        }

当然如果想要改为同步的上传文件只要调用 mOkHttpClient.newCall(request).execute()就可以了。
在wangshu.txt文件中有一行字“Android网络编程(六)OkHttp3用法全解析”我们运行程序点击发送文件按钮,最终请求网络返回的结果就是我们txt文件中的内容 :

这里写图片描述

当然不要忘了添加如下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

二.异步下载文件

下载文件同样在上一篇没有讲到,实现起来比较简单,在这里下载一张图片,我们得到Response后将流写进我们指定的图片文件中就可以了。

private void downAsynFile() {        mOkHttpClient = new OkHttpClient();        String url = "http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";        Request request = new Request.Builder().url(url).build();        mOkHttpClient.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) {                InputStream inputStream = response.body().byteStream();                FileOutputStream fileOutputStream = null;                try {                    fileOutputStream = new FileOutputStream(new File("/sdcard/wangshu.jpg"));                    byte[] buffer = new byte[2048];                    int len = 0;                    while ((len = inputStream.read(buffer)) != -1) {                        fileOutputStream.write(buffer, 0, len);                    }                    fileOutputStream.flush();                } catch (IOException e) {                    Log.i("wangshu", "IOException");                    e.printStackTrace();               }               Log.d("wangshu", "文件下载成功");           }       });   }

三.异步上传Multipart文件

这种场景很常用,我们有时会上传文件同时还需要传其他类型的字段,OkHttp3实现起来很简单,需要注意的是没有服务器接收我这个Multipart文件,所以这里只是举个例子,具体的应用还要结合实际工作中对应的服务器。
首先定义上传文件类型:

private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private void sendMultipart(){    mOkHttpClient = new OkHttpClient();    RequestBody requestBody = new MultipartBody.Builder()            .setType(MultipartBody.FORM)            .addFormDataPart("title", "wangshu")            .addFormDataPart("image", "wangshu.jpg",                    RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/wangshu.jpg")))            .build();    Request request = new Request.Builder()            .header("Authorization", "Client-ID " + "...")            .url("https://api.imgur.com/3/image")            .post(requestBody)            .build();   mOkHttpClient.newCall(request).enqueue(new Callback() {       @Override       public void onFailure(Call call, IOException e) {       }       @Override       public void onResponse(Call call, Response response) throws IOException {           Log.i("wangshu", response.body().string());       }   });}



1 0
原创粉丝点击