OkHttp总结

package com.jimmy.sample;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.net.Uri;

import android.os.Environment;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.ImageView;

import android.widget.TextView;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import okhttp3.Call;

import okhttp3.Callback;

import okhttp3.FormBody;

import okhttp3.MediaType;

import okhttp3.MultipartBody;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.RequestBody;

import okhttp3.Response;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.l;

import static org.bouncycastle.crypto.tls.ConnectionEnd.client;

public class MainActivityextends AppCompatActivity {

private TextViewmTvResult;

    private ImageViewmyImgV;

    private StringmBaseUrl ="http://192.168.1.235:8080/mywebnew/";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mTvResult = (TextView) findViewById(R.id.text_result);

        myImgV = (ImageView) findViewById(R.id.myImgV);

    }

public void doPost(View view) {

//1 拿到okhttpclient 对象

        OkHttpClient okHttpClient =new OkHttpClient();

        //2 构造request

//2.1 构造Formbody

        FormBody formBody =new FormBody.Builder()

.add("username", "lisi")

.add("password", "888")

.build();

        Request request =new Request.Builder().url(mBaseUrl +"login").post(formBody).build();

        okHttpClient.newCall(request).enqueue(new Callback() {

@Override

            public void onFailure(Call call, IOException e) {

}

@Override

            public void onResponse(Call call, Response response)throws IOException {

}

});

    }

//post json 字符串

    public void doPostString(View view) {

OkHttpClient okHttpClient =new OkHttpClient();

        RequestBody formBody = FormBody.create(MediaType.parse("text/plain;chaset=utf-8"), "{username:zhangsan,password:123}");

        Request request =new Request.Builder().url(mBaseUrl +"postString").post(formBody).build();

        okHttpClient.newCall(request).enqueue(new Callback() {

@Override

            public void onFailure(Call call, IOException e) {

}

@Override

            public void onResponse(Call call, Response response)throws IOException {

}

});

    }

//post file

    public void doPostFile(View view) {

File file =new File(Environment.getExternalStorageDirectory(), "me.jpg");

        if (!file.exists()) {

L.e(file.getAbsolutePath() +" not exist");

return;

        }

OkHttpClient okHttpClient =new OkHttpClient();

        // MediaType 可以通过搜索 mime type 得到

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

        Request request =new Request.Builder().url(mBaseUrl +"postFile").post(requestBody).build();

        okHttpClient.newCall(request).enqueue(new Callback() {

@Override

            public void onFailure(Call call, IOException e) {

}

@Override

            public void onResponse(Call call, Response response)throws IOException {

}

});

    }

//上传表单

    public void doUpload(View view) {

File file =new File(Environment.getExternalStorageDirectory(), "me.jpg");

        if (!file.exists()) {

L.e(file.getAbsolutePath() +" no exist");

return;

        }

OkHttpClient okHttpClient =new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

        MultipartBody multipartBody =new MultipartBody.Builder()

// 设置type为"multipart/form-data",不然无法上传参数

                .setType(MultipartBody.FORM)

.addFormDataPart("username", "zhangsan")

.addFormDataPart("password", "mima")

.addFormDataPart("mPhoto", "wo.jpg", requestBody)

.build();

        CountingRequestBody countingRequestBody =new CountingRequestBody(multipartBody, new CountingRequestBody.Listener() {

@Override

            public void onRequestProgress(long byteWrited, long contentLength) {

L.e(byteWrited+" / "+contentLength);

            }

});

        Request request =new Request.Builder().url(mBaseUrl +"uploadInfo").post(countingRequestBody).build();

        okHttpClient.newCall(request).enqueue(new Callback() {

@Override

            public void onFailure(Call call, IOException e) {

}

@Override

            public void onResponse(Call call, Response response)throws IOException {

}

});

    }

//上传带进度

    public void doUploadWithProgress(View view) {

File file =new File(Environment.getExternalStorageDirectory(), "me.jpg");

        if (!file.exists()) {

L.e(file.getAbsolutePath() +" no exist");

return;

        }

OkHttpClient okHttpClient =new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

        MultipartBody multipartBody =new MultipartBody.Builder()

// 设置type为"multipart/form-data",不然无法上传参数

                .setType(MultipartBody.FORM)

.addFormDataPart("username", "zhangsan")

.addFormDataPart("password", "mima")

.addFormDataPart("mPhoto", "wo.jpg", requestBody)

.build();

        Request request =new Request.Builder().url(mBaseUrl +"uploadInfo").post(multipartBody).build();

        okHttpClient.newCall(request).enqueue(new Callback() {

@Override

            public void onFailure(Call call, IOException e) {

}

@Override

            public void onResponse(Call call, Response response)throws IOException {

}

});

    }

//下载文件

    public void doDownload(View view) {

//1 拿到okhttpclient 对象

        OkHttpClient okHttpClient =new OkHttpClient();

        //Request 基于构造者模式

//2 构造request

        Request.Builder builder =new Request.Builder();

        Request request = builder.get().url(mBaseUrl +"files/ni.jpg").build();

        //3 执行call

//Response response=call.execute();

        okHttpClient.newCall(request).enqueue(new Callback() {

@Override

            public void onFailure(Call call, IOException e) {

L.e("onFailure" + e.getMessage());

                e.printStackTrace();

            }

@Override

            public void onResponse(Call call, Response response)throws IOException {

/* L.e("onResponse:");

InputStream is = response.body().byteStream();

int len = 0;

File file = new File(Environment.getExternalStorageDirectory(), "nihao.jpg");

byte[] buf = new byte[128];

FileOutputStream fos = new FileOutputStream(file);

while ((len=is.read(buf))!=-1) {

fos.write(buf,0,len);

}

fos.flush();

fos.close();

is.close();

runOnUiThread(new Runnable() {

@Override

public void run() {

myImgV.setImageURI(Uri.parse(Environment.getExternalStorageDirectory() + "/nihao.jpg"));

}

});

L.e("download success");*/

//带有下载进度

                L.e("onResponse:");

                //数据总长度

              final long total =response.body().contentLength();

                long sum=0L;

                InputStream is = response.body().byteStream();

                int len =0;

                File file =new File(Environment.getExternalStorageDirectory(), "nihao.jpg");

                byte[] buf =new byte[128];

                FileOutputStream fos =new FileOutputStream(file);

                while ((len = is.read(buf)) != -1) {

fos.write(buf, 0, len);

                  sum+=len;

                    L.e(sum+"/"+total);

                    final long finalSum=sum;

                    runOnUiThread(new Runnable() {

@Override

                        public void run() {

mTvResult.setText(finalSum+"/"+total);

                            myImgV.setImageURI(Uri.parse(Environment.getExternalStorageDirectory() +"/nihao.jpg"));

                        }

});

                }

fos.flush();

                fos.close();

                is.close();

                runOnUiThread(new Runnable() {

@Override

                    public void run() {

myImgV.setImageURI(Uri.parse(Environment.getExternalStorageDirectory() +"/nihao.jpg"));

                    }

});

                L.e("download success");

            }

});

    }

public void doGet(View view)throws IOException {

//一个请求分4步

//1 拿到okhttpclient 对象

        OkHttpClient okHttpClient =new OkHttpClient();

        //Request 基于构造者模式

//2 构造request

        Request.Builder builder =new Request.Builder();

        Request request = builder.get().url(mBaseUrl +"login?username=zhangsan&password=444").build();

        //3 执行call

//Response response=call.execute();

        okHttpClient.newCall(request).enqueue(new Callback() {

@Override

            public void onFailure(Call call, IOException e) {

L.e("onFailure" + e.getMessage());

                e.printStackTrace();

            }

@Override

            public void onResponse(Call call, Response response)throws IOException {

L.e("onResponse:");

                final String res = response.body().string();

                L.e(res);

                runOnUiThread(new Runnable() {

@Override

                    public void run() {

mTvResult.setText(res);

                    }

});

            }

});

    }

}

你可能感兴趣的:(OkHttp总结)