java 中OkHttp的使用方法及实例
java 中OkHttp的使用方法及实例
概述
准备研究Retrofit,而它是依赖OkHttp的,所以先使用一下OkHttp,不深究源码,只探究使用方法。以后有机会再翻查源码。
在进行之前,首先需要2个jar包,其中一个是okHttp的jar包,github上可以下载,另一个是它的依赖包,这个很关键,没有它,项目就无法运行。
OkHttp请求的2种方式
不难猜测,涉及到网络请求,那么无非2种方式,一种是使用回调,另一种则是开启子线程执行。
第一种:开启子线程执行
OkHttpClientclient=newOkHttpClient(); Requestbuild=newRequest.Builder().url(url).build(); try{Responseexecute=client.newCall(build).execute(); if(execute.isSuccessful()){ System.out.println("wiselyaaa"); }else{ System.out.println("wiselybbb"); } }catch(IOExceptione){ e.printStackTrace(); }
第二种:使用回调,我个人最喜欢使用这种。(PS:觉得自己真是tooyoungtoosimple!!本来以为回调的方法是在主线程,结果发现,竟然是子线程,子线程....)
OkHttpClientclient=newOkHttpClient(); Requestbuild=newRequest.Builder().url(url).build(); client.newCall(build).enqueue(newCallback(){ @Override publicvoidonResponse(Responsearg0)throwsIOException{ System.out.println("wiselysuccess"); } @Override publicvoidonFailure(Requestarg0,IOExceptionarg1){ System.out.println("wiselyfailure"); } });
OkHttp之get请求
1、获取图片
OkHttpClientclient=newOkHttpClient(); Requestbuild=newRequest.Builder().url(url).build(); client.newCall(build).enqueue(newCallback(){ @Override publicvoidonResponse(Responseresponse)throwsIOException{ //byte[]bytes=response.body().bytes(); InputStreamis=response.body().byteStream(); Optionsoptions=newBitmapFactory.Options(); options.inSampleSize=8; //Bitmapbitmap=BitmapFactory.decodeByteArray(bytes,0,bytes.length,options); Bitmapbitmap=BitmapFactory.decodeStream(is,null,options); Messagemsg=handler.obtainMessage(); msg.obj=bitmap; handler.sendMessage(msg); } @Override publicvoidonFailure(Requestarg0,IOExceptionarg1){ System.out.println("wiselyfail:"+arg1.getCause().getMessage()); } });
只写了关键代码,并未写handler的相关代码。
获取网络图片有2种方式,1是获取byte数组,2是获取输入流。注意,onResponse在子线程中...
OkHttp之post请求
比起get请求,post请求的分类略多。
1、首先是最常用的表单提交。
OkHttpClientclient=newOkHttpClient(); RequestBodybody=newFormEncodingBuilder() .add("userName","13363114390") .add("password","200820e3227815ed1756a6b531e7e0d2").build(); Requestbuild=newRequest.Builder().url(url).post(body).build(); client.newCall(build).enqueue(newCallback(){ @Override publicvoidonResponse(Responseresponse)throwsIOException{ Stringlenght=response.header("Content-Length"); System.out.println("wisely--lenght:"+lenght); LoginResponseloginResponse=newGson().fromJson(response.body().charStream(),LoginResponse.class); System.out.println("wisely---"+loginResponse.getMessage()); } @Override publicvoidonFailure(Requestarg0,IOExceptionarg1){ System.out.println("wisely-----fail"); } });
StringtokeId; booleanresult; publicbooleanisResult(){ returnresult; } publicvoidsetResult(booleanresult){ this.result=result; } publicStringgetMessage(){ returnmessage; } publicvoidsetMessage(Stringmessage){ this.message=message; } publicStringgetTokeId(){ returntokeId; } publicvoidsetTokeId(StringtokeId){ this.tokeId=tokeId; } }
上面的是一个简单的登录表单的提交,其中将返回的json数据封装到了一个bean中。除了能够获取json数据外,还能获取到各个消息头。
2、上传图片
这是我最关心的一个功能,实验证明,okHttp上传图片的功能确实强大,支持多图片上传。
privateMediaTypePNG=MediaType.parse("application/octet-stream");
OkHttpClientclient=newOkHttpClient(); RequestBodybody=newMultipartBuilder() .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(); Requestrequest=newRequest.Builder().url(url) .post(body).build(); client.newCall(request).enqueue(newCallback(){ @Override publicvoidonResponse(Responseresponse)throwsIOException{ if(response.isSuccessful()){ UploadPNGResponseuploadPNGResponse=newGson().fromJson(response.body().charStream(),UploadPNGResponse.class); Stringmsg=uploadPNGResponse.getMsg(); List list=uploadPNGResponse.getList(); for(Stringstring:list){ System.out.println("wisely---path:"+string); } } } @Override publicvoidonFailure(Requestarg0,IOExceptionarg1){ System.out.println("wisely---fail--"+arg1.getCause().getMessage()); } });
classUploadPNGResponse{ Stringmsg; booleanresult; Listlist; publicStringgetMsg(){ returnmsg; } publicvoidsetMsg(Stringmsg){ this.msg=msg; } publicbooleanisResult(){ returnresult; } publicvoidsetResult(booleanresult){ this.result=result; } publicList getList(){ returnlist; } publicvoidsetList(List list){ this.list=list; } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!