java中OkHttp的使用方法及实例

时间:2021-05-19

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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章