java 中OkHttp的使用方法及实例详解

这篇文章主要介绍了java 中OkHttp的使用方法及实例的相关资料,需要的朋友可以参考下

java 中OkHttp的使用方法及实例

概述

准备研究Retrofit,而它是依赖OkHttp的,所以先使用一下OkHttp,不深究源码,只探究使用方法。以后有机会再翻查源码。

在进行之前,首先需要2个jar包,其中一个是okHttp的jar包,github上可以下载,另一个是它的依赖包,这个很关键,没有它,项目就无法运行。

OkHttp请求的2种方式

不难猜测,涉及到网络请求,那么无非2种方式,一种是使用回调,另一种则是开启子线程执行。

第一种:开启子线程执行

OkHttpClient client = new OkHttpClient(); Request build = new Request.Builder().url(url).build(); try { <span style="white-space:pre">  </span>Response execute = client.newCall(build).execute();   if(execute.isSuccessful()){     System.out.println("wisely aaa");   } else {     System.out.println("wisely bbb");   } } catch (IOException e) {   e.printStackTrace(); }

第二种:使用回调,我个人最喜欢使用这种。(PS:觉得自己真是too young too simple!!本来以为回调的方法是在主线程,结果发现,竟然是子线程,子线程….)

OkHttpClient client = new OkHttpClient(); Request build = new Request.Builder().url(url).build(); client.newCall(build).enqueue(new Callback() {    @Override   public void onResponse(Response arg0) throws IOException {     System.out.println("wisely  success");   }    @Override   public void onFailure(Request arg0, IOException arg1) {     System.out.println("wisely  failure");   } });

OkHttp之get请求

1、获取图片

OkHttpClient client = new OkHttpClient();      Request build = new Request.Builder().url(url).build(); client.newCall(build).enqueue(new Callback() {          @Override   public void onResponse(Response response) throws IOException { //   byte[] bytes = response.body().bytes();     InputStream is = response.body().byteStream();     Options options = new BitmapFactory.Options();     options.inSampleSize = 8; //   Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,options);     Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);     Message msg = handler.obtainMessage();     msg.obj = bitmap;     handler.sendMessage(msg);   }        @Override   public void onFailure(Request arg0, IOException arg1) {     System.out.println("wisely fail:"+arg1.getCause().getMessage());   } });

只写了关键代码,并未写handler的相关代码。

获取网络图片有2种方式,1是获取byte数组,2是获取输入流。注意,onResponse在子线程中…

OkHttp之post请求

比起get请求,post请求的分类略多。

1、首先是最常用的表单提交。

OkHttpClient client = new OkHttpClient();  RequestBody body = new FormEncodingBuilder()     .add("userName", "13363114390")     .add("password", "200820e3227815ed1756a6b531e7e0d2").build();  Request build = new Request.Builder().url(url).post(body).build(); client.newCall(build).enqueue(new Callback() {    @Override   public void onResponse(Response response) throws IOException {     String lenght = response.header("Content-Length");     System.out.println("wisely--lenght:" + lenght);      LoginResponse loginResponse = new Gson().fromJson(response.body().charStream(), LoginResponse.class);     System.out.println("wisely---" + loginResponse.getMessage());   }    @Override   public void onFailure(Request arg0, IOException arg1) {     System.out.println("wisely-----fail");   } });
String tokeId;   boolean result;    public boolean isResult() {     return result;   }    public void setResult(boolean result) {     this.result = result;   }    public String getMessage() {     return message;   }    public void setMessage(String message) {     this.message = message;   }    public String getTokeId() {     return tokeId;   }    public void setTokeId(String tokeId) {     this.tokeId = tokeId;   }  }

上面的是一个简单的登录表单的提交,其中将返回的json数据封装到了一个bean中。除了能够获取json数据外,还能获取到各个消息头。

2、上传图片

这是我最关心的一个功能,实验证明,okHttp上传图片的功能确实强大,支持多图片上传。

private MediaType PNG = MediaType.parse("application/octet-stream");
OkHttpClient client = new OkHttpClient();      RequestBody body = new MultipartBuilder()     .type(MultipartBuilder.FORM)     .addPart(Headers.of("Content-Disposition","form-data; name=\&;files\&;;filename=\&;img1.jpg\&;"),RequestBody.create(PNG, file1))     .addPart(Headers.of("Content-Disposition","form-data; name=\&;files\&;;filename=\&;img2.jpg\&;"),RequestBody.create(PNG, file2)).build();      Request request = new Request.Builder()   <span style="white-space:pre">  </span>.url(url)     .post(body).build(); client.newCall(request).enqueue(new Callback() {          @Override   public void onResponse(Response response) throws IOException {              if(response.isSuccessful()){       UploadPNGResponse uploadPNGResponse = new Gson().fromJson(response.body().charStream(), UploadPNGResponse.class);       String msg = uploadPNGResponse.getMsg();                  List<String> list = uploadPNGResponse.getList();       for (String string : list) {         System.out.println("wisely---path:"+string);       }                }   }          @Override   public void onFailure(Request arg0, IOException arg1) {     System.out.println("wisely---fail--"+arg1.getCause().getMessage());   } });
class UploadPNGResponse{  String msg;   boolean result;   List<String> list;   public String getMsg() {     return msg;   }   public void setMsg(String msg) {     this.msg = msg;   }   public boolean isResult() {     return result;   }   public void setResult(boolean result) {     this.result = result;   }   public List<String> getList() {     return list;   }   public void setList(List<String> list) {     this.list = list;   } }

以上就是java 中OkHttp的使用方法及实例详解的详细内容,更多请关注其它相关文章!

没有人陪你走一辈子,所以你要适应孤独,

java  中OkHttp的使用方法及实例详解

相关文章:

你感兴趣的文章:

标签云: