国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android-Okhttp的使用解析

2019-12-12 03:25:23
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

okhttp是Android6.0推出的網(wǎng)絡(luò)框架。由于谷歌在Android6.0的之后,將HttpClient相關(guān)屬性取消掉,導(dǎo)致Volley框架不能正常使用。所以才有了今天的Okhttp。

 Okhttp進(jìn)行網(wǎng)絡(luò)訪問(wèn)通常有兩種方式,一種是get請(qǐng)求,還有一種叫做post請(qǐng)求。

1、OKhttp的get請(qǐng)求

通常,我們使用get方式來(lái)請(qǐng)求一個(gè)網(wǎng)站,是依靠url地址的。Okhttp使用get方式來(lái)請(qǐng)求網(wǎng)站通常有如下的步驟:

A、創(chuàng)建OkhttpClient的變量,這個(gè)變量相當(dāng)于是一個(gè)全局的執(zhí)行者。主要的網(wǎng)絡(luò)操作是依靠它來(lái)進(jìn)行的。

B、創(chuàng)建一個(gè)builder對(duì)象。

C、利用builder對(duì)象創(chuàng)建一個(gè)Request對(duì)象。

D、使用全局執(zhí)行者來(lái)創(chuàng)建一個(gè)Call對(duì)象。

E、通過(guò)Call對(duì)象來(lái)進(jìn)行網(wǎng)絡(luò)連接。

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請(qǐng)求

Post請(qǐng)求與get請(qǐng)求有些不一樣。get請(qǐng)求主要的功能是從服務(wù)器上獲取數(shù)據(jù),而Post請(qǐng)求則是向服務(wù)器提交數(shù)據(jù)。

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、服務(wù)器端接收客戶端傳過(guò)來(lái)的字符串

客戶端的代碼:

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

服務(wù)器端的代碼:

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, 0, len));    }    System.out.println(sb.toString());    return null;  }

服務(wù)器端如果要接收客戶端的數(shù)據(jù),則需要接收request;如果服務(wù)器端想要給客戶端傳數(shù)據(jù),則需要通過(guò)response來(lái)傳遞。

4、使用post方式進(jìn)行文件的傳輸

客戶端的代碼

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 + "login").post(requestBody).build();    Call newCall = mOkHttpClient.newCall(request);    executeCall(newCall);  }

關(guān)于選擇文件的代碼--抄襲網(wǎng)絡(luò)上的代碼,并不是自己寫(xiě)的

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

在進(jìn)行這個(gè)的操作的時(shí)候,一定要記住增加讀和寫(xiě)的權(quán)限,否則會(huì)上傳失敗的。

服務(wù)器端的代碼

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, 0, len);    }    fos.flush();    fos.close();    return null;  }

上面顯示的files文件,在Tomcat的webapps下的工程名名文件下的fies文件夾(才開(kāi)始是沒(méi)有這個(gè)文件夾的,需要手動(dòng)自己創(chuàng)建)。

5.使用Post方式來(lái)上傳文件

客戶端代碼:

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

服務(wù)器端的代碼:

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

在上傳文件的時(shí)候,有一個(gè)小細(xì)節(jié)都注意到:就是Tomcat服務(wù)器只允許上傳2m以下的文件。要想上傳大文件,就必須在struct文件中加一句:<constant name="struts.multipart.maxSize" value="1024000000"/>數(shù)字表示自定義大小的限制。

6.上傳文件時(shí),進(jìn)度的顯示問(wèn)題

在寫(xiě)代碼的時(shí)候我們知道,我們不能直接獲得上傳文件的進(jìn)度。因?yàn)檫@些數(shù)據(jù)都是封裝在RequestBody里面的,要想使用只有通過(guò)回調(diào)接口來(lái)實(shí)現(xiàn)。

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 前世訣別的一紙書(shū) 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", "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);

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 梓潼县| 呼玛县| 望奎县| 南江县| 油尖旺区| 金门县| 芮城县| 宽甸| 滨海县| 随州市| 台山市| 重庆市| 互助| 富源县| 南岸区| 商城县| 新巴尔虎右旗| 前郭尔| 饶河县| 兴化市| 华坪县| 娱乐| 宁安市| 双牌县| 定日县| 道真| 澳门| 武胜县| 曲水县| 玉龙| 靖安县| 乌鲁木齐县| 定陶县| 招远市| 德钦县| 琼中| 唐海县| 中超| 巴塘县| 上高县| 锡林郭勒盟|