okhttp是AndroID6.0推出的网络框架。由于谷歌在AndroID6.0的之后,将httpClIEnt相关属性取消掉,导致Volley框架不能正常使用。所以才有了今天的Okhttp。
Okhttp进行网络访问通常有两种方式,一种是get请求,还有一种叫做post请求。
1、OKhttp的get请求
通常,我们使用get方式来请求一个网站,是依靠URL地址的。Okhttp使用get方式来请求网站通常有如下的步骤:
A、创建OkhttpClIEnt的变量,这个变量相当于是一个全局的执行者。主要的网络 *** 作是依靠它来进行的。
B、创建一个builder对象。
C、利用builder对象创建一个Request对象。
D、使用全局执行者来创建一个Call对象。
E、通过Call对象来进行网络连接。
public voID doGet(VIEw vIEw) { Request.Builder builder = new Request.Builder(); Request request = builder.get().url(urlString + "username=pby&userPassword=123").build(); Call newCall = mOkhttpClIEnt.newCall(request); //newCall.execute() newCall.enqueue(new Callback() { @OverrIDe public voID onFailure(Request request,IOException e) { L.e("失败了"); } @OverrIDe public voID onResponse(Response response) throws IOException { String string = response.body().string(); L.e(string); } }); }
2、Okhttp的Post请求
Post请求与get请求有些不一样。get请求主要的功能是从服务器上获取数据,而Post请求则是向服务器提交数据。
public voID doPost(VIEw vIEw) { FormEnCodingBuilder requestbodyBuilder = new FormEnCodingBuilder(); Requestbody requestbody = requestbodyBuilder.add("username","pby").add("userPassword","123").build(); Request.Builder builder = new Request.Builder(); Request request = builder.url(urlString).post(requestbody).build(); Call newCall = mOkhttpClIEnt.newCall(request); executeCall(newCall); }
3、服务器端接收客户端传过来的字符串
客户端的代码:
public voID dopoststring(VIEw vIEw) { Requestbody requestbody = Requestbody.create(MediaType.parse("text/plain;charset = utf-8"),"{name = pby,password = 1234}"); Request.Builder builder = new Request.Builder(); Request request = builder.url(urlString + "dopoststring").post(requestbody).build(); Call newCall = mOkhttpClIEnt.newCall(request); executeCall(newCall); }
服务器端的代码:
public String dopoststring() throws IOException { httpServletRequest request = ServletActionContext.getRequest(); ServletinputStream inputStream = request.getinputStream(); StringBuilder sb = new StringBuilder(); int len = 0; byte []buff = new byte[1024]; while((len = inputStream.read(buff)) != -1) { sb.append(new String(buff,len)); } System.out.println(sb.toString()); return null; }
服务器端如果要接收客户端的数据,则需要接收request;如果服务器端想要给客户端传数据,则需要通过response来传递。
4、使用post方式进行文件的传输
客户端的代码
public voID doPost(VIEw vIEw) { FormEnCodingBuilder requestbodyBuilder = new FormEnCodingBuilder(); Requestbody requestbody = requestbodyBuilder.add("username","123").build(); Request.Builder builder = new Request.Builder(); Request request = builder.url(urlString + "login").post(requestbody).build(); Call newCall = mOkhttpClIEnt.newCall(request); executeCall(newCall); }
关于选择文件的代码--抄袭网络上的代码,并不是自己写的
private voID showfileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addcategory(Intent.category_OPENABLE); try { startActivityForResult( Intent.createChooser(intent,"Select a file to Upload"),1); } catch (androID.content.ActivityNotFoundException ex) { Toast.makeText(this,"Please install a file Manager.",Toast.LENGTH_SHORT).show(); } } @OverrIDe protected voID onActivityResult(int requestCode,int resultCode,Intent data) { switch (requestCode) { case 1: if (resultCode == RESulT_OK) { // Get the Uri of the selected file Uri uri = data.getData(); String path = fileUtils.getPath(this,uri); if(path != null) { postfile(path); } } break; } super.onActivityResult(requestCode,resultCode,data); }
在进行这个的 *** 作的时候,一定要记住增加读和写的权限,否则会上传失败的。
服务器端的代码
public String dopostfile() throws IOException { httpServletRequest request = ServletActionContext.getRequest(); ServletinputStream inputStream = request.getinputStream(); String dir = ServletActionContext.getServletContext().getRealPath("files"); file file = new file(dir,"abc.jpg"); fileOutputStream fos = new fileOutputStream(file); int len = 0; byte [] buff = new byte[1024]; while((len = inputStream.read(buff)) != -1) { fos.write(buff,len); } fos.flush(); fos.close(); return null; }
上面显示的files文件,在Tomcat的webapps下的工程名名文件下的fIEs文件夹(才开始是没有这个文件夹的,需要手动自己创建)。
5.使用Post方式来上传文件
客户端代码:
private voID upLoadfile(String path) { file file = new file(path); if(!file.exists()) { return ; } MultipartBuilder multipartBuilder = new MultipartBuilder(); Requestbody requestbody = multipartBuilder.type(MultipartBuilder.FORM) .addFormDataPart("username","pby") .addFormDataPart("userPassword","123") .addFormDataPart("mfile",file.getname(),Requestbody.create(MediaType.parse("application/octet-stream"),file)).build();// CountingRequestbody countingRequestbody = new CountingRequestbody(requestbody,new CountingRequestbody.MyListener() {// @OverrIDe// public voID onRequestProgress(int byteWriteCount,int TotalCount) {// L.e(byteWriteCount + " / " + TotalCount);// }// }); Request.Builder builder = new Request.Builder(); //Request request = builder.url(urlString + "doUpLoadfile").post(countingRequestbody).build(); Request request = builder.url(urlString + "doUpLoadfile").post(requestbody).build(); Call newCall = mOkhttpClIEnt.newCall(request); executeCall(newCall); }
服务器端的代码:
public String doUpLoadfile() { if(mfile == null) { System.out.println(mfilefilename+" is null.."); return null; } String dir = ServletActionContext.getServletContext().getRealPath("files"); file file = new file(dir,mfilefilename); try { fileUtils.copyfile(mfile,file); } catch (IOException e) { // Todo auto-generated catch block e.printstacktrace(); } return null; }
在上传文件的时候,有一个小细节都注意到:就是Tomcat服务器只允许上传2m以下的文件。要想上传大文件,就必须在struct文件中加一句:<constant name="struts.multipart.maxSize" value="1024000000"/>数字表示自定义大小的限制。
6.上传文件时,进度的显示问题
在写代码的时候我们知道,我们不能直接获得上传文件的进度。因为这些数据都是封装在Requestbody里面的,要想使用只有通过回调接口来实现。
package com.example.androID_okhttp;import com.squareup.okhttp.MediaType;import com.squareup.okhttp.Requestbody;import java.io.IOException;import okio.Buffer;import okio.BufferedSink;import okio.ForwardingSink;import okio.Okio;import okio.Sink;/** * Created by 前世诀别的一纸书 on 2017/3/5. */public class CountingRequestbody extends Requestbody { private Requestbody delegate = null; private MyListener mListener= null; private CountingSink mCountSink = null; public interface MyListener { voID onRequestProgress(int byteWriteCount,int TotalCount); } public CountingRequestbody(Requestbody requestbody,MyListener Listener) { delegate = requestbody; mListener = Listener; } @OverrIDe public MediaType ContentType() { return delegate.ContentType(); } @OverrIDe public voID writeto(BufferedSink sink) throws IOException { mCountSink = new CountingSink(sink); BufferedSink bs = Okio.buffer(mCountSink); delegate.writeto(bs); bs.flush(); } private class CountingSink extends ForwardingSink{ private int byteWriteCount = 0; public CountingSink(Sink delegate) { super(delegate); } @OverrIDe public voID write(Buffer source,long byteCount) throws IOException { super.write(source,byteCount); byteWriteCount += byteCount; mListener.onRequestProgress(byteWriteCount,(int) contentLength()); } } @OverrIDe public long contentLength() throws IOException { return delegate.contentLength(); }}
MultipartBuilder multipartBuilder = new MultipartBuilder(); Requestbody requestbody = multipartBuilder.type(MultipartBuilder.FORM) .addFormDataPart("username",file)).build(); CountingRequestbody countingRequestbody = new CountingRequestbody(requestbody,new CountingRequestbody.MyListener() { @OverrIDe public voID onRequestProgress(int byteWriteCount,int TotalCount) { L.e(byteWriteCount + " / " + TotalCount); } }); Request.Builder builder = new Request.Builder(); Request request = builder.url(urlString + "doUpLoadfile").post(countingRequestbody).build(); //Request request = builder.url(urlString + "doUpLoadfile").post(requestbody).build(); Call newCall = mOkhttpClIEnt.newCall(request);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的Android-Okhttp的使用解析全部内容,希望文章能够帮你解决Android-Okhttp的使用解析所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)