原生OKHttp以及OKHttpUtil的使用

Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient。
尽管Google在大部分安卓版本中推荐使用HttpURLConnection,但是这个类相比HttpClient实在是太难用,太弱爆了。OkHttp 处理了很多网络疑难杂症:会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果你用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。

以下是我写的一个OKHttp原生API的使用以及国内某大牛封装的OKHttpUtil的使用方法Demo

package com.jereh.learnbymyself.OKHttp;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jereh.learnbymyself.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OKHttpActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int POST = 2;
    private static final int GET = 1;
    private Button btn_get_post, btn_get_okhttputils, btn_downloadfile,btn_uploadfile,btn_image;
    private TextView tv_result;
    private ProgressBar progressBar;
    private ImageView iv_icon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_okhttp);
        btn_get_post = (Button) findViewById(R.id.btn_get_post);
        tv_result = (TextView) findViewById(R.id.tv_result);
        btn_get_okhttputils = (Button) findViewById(R.id.btn_get_okhttputils);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btn_downloadfile = (Button) findViewById(R.id.btn_downloadfile);
        btn_uploadfile = (Button) findViewById(R.id.btn_uploadfile);
        btn_image = (Button) findViewById(R.id.btn_image);
        iv_icon = (ImageView) findViewById(R.id.iv_icon);
        tv_result.setOnClickListener(this);
        btn_uploadfile.setOnClickListener(this);
        btn_get_post.setOnClickListener(this);
        btn_get_okhttputils.setOnClickListener(this);
        btn_downloadfile.setOnClickListener(this);
        btn_image.setOnClickListener(this);
    }

    private static final String TAG = "haoren";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_get_post: //使用原生的OKHttp 请求网络,get和post:
                tv_result.setText("");
                getDataFromPost();
                break;
            case R.id.btn_get_okhttputils: //使用封装util
                getDataByUtil();
                break;
            case R.id.btn_downloadfile:
                downloadFile();
                break;
            case R.id.btn_uploadfile:
                fileUpload();
                break;
            case R.id.btn_image:
                getImg();
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //获取数据
                    tv_result.setText((String) msg.obj);
                    break;
                case POST:
                    //获取数据
                    tv_result.setText((String) msg.obj);
                    break;
            }
        }
    };

    /**
    * 使用get请求
    */
    private void getDataFromGet() {
        new Thread() {
            @Override
            public void run() {
                try {
                    String result = get(url);
                    Log.d(TAG, "onClick: " + result.toString());
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    /**
    * 使用post请求
    */
    private void getDataFromPost() {
        new Thread() {
            @Override
            public void run() {
                try {
                    String result = post(url, "");
                    Log.d(TAG, "onClick: " + result.toString());
                    Message msg = new Message();
                    msg.what = POST;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    OkHttpClient client = new OkHttpClient();

    private String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=1&offset=0";

    /**
    * http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=1&offset=0
    * get请求  网络连接
    *
    * @param url
    * @return
    * @throws IOException
    */
    private String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    /**
    * post 请求
    *
    * @param url
    * @return
    * @throws IOException
    */
    private String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
    * 使用OKHttpUtil
    */
    public void getDataByUtil() {
        OkHttpUtils
                .post()
                .url(url)
                .id(100)
                .build()
                .execute(new MyStringCallback());
    }

    public class MyStringCallback extends StringCallback {
        @Override
        public void onBefore(Request request, int id) {
            setTitle("loading...");
        }

        @Override
        public void onAfter(int id) {
            setTitle("Sample-okHttp");
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();
            tv_result.setText("onError:" + e.getMessage());
        }

        @Override
        public void onResponse(String response, int id) {
            Log.e(TAG, "onResponse:complete");
            tv_result.setText("onResponse:" + response);

            switch (id) {
                case 100:
                    Toast.makeText(OKHttpActivity.this, "http", Toast.LENGTH_SHORT).show();
                    break;
                case 101:
                    Toast.makeText(OKHttpActivity.this, "https", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        @Override
        public void inProgress(float progress, long total, int id) {
            Log.e(TAG, "inProgress:" + progress);
            progressBar.setProgress((int) (100 * progress));
        }
    }

    /**
    * 下载大文件
    */
    private void downloadFile() {
        String url = "http://dl.download.csdn.net/down10/20150110/225fe49dc61fba661b2b06b27caf9e16.jar?response-content-disposition=attachment%3Bfilename%3D%22gson-2.3.1.jar%22&OSSAccessKeyId=9q6nvzoJGowBj4q1&Expires=1486181058&Signature=O6n47e7oK3JwnYl%2FaLdcXHy8KT0%3D";
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(),
                        "gson.jar") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Log.e(TAG, "onResponse: " + response.getAbsolutePath());
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        progressBar.setProgress((int) (100 * progress));
                    }

                });
    }

    private String address = "http://172.20.10.2:8080/FileUpload/index.jsp";
    /**
    * 文件上传
    */
    private void fileUpload(){
        File file = new File(Environment.getExternalStorageDirectory(), "gson.jar");
        File file2 = new File(Environment.getExternalStorageDirectory(), "123.jpg");
        if (!file.exists() || !file2.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        Map params = new HashMap<>();
        params.put("username", "haoren");
        params.put("password", "123");
        String mBaseUrl = "http://192.168.155.1:8080/FileUpload/FileUploadServlet";
        OkHttpUtils.post()
                .addFile("mFile", "gson.jar", file)
                .addFile("mFile", "123.jpg", file2)
                .url(mBaseUrl)
                .params(params)
                .build()
                .execute(new MyStringCallback());
    }
    /**
    * 请求图片
    */
    private void getImg(){
        tv_result.setText("");
        String url = "http://images.csdn.net/20150817/1.jpg";
        OkHttpUtils
                .get()
                .url(url)
                .tag(this)
                .build()
                .connTimeOut(2000)
                .readTimeOut(2000)
                .writeTimeOut(2000)
                .execute(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        tv_result.setText(e.getMessage());
                    }

                    @Override
                    public void onResponse(Bitmap response, int id) {
                        iv_icon.setImageBitmap(response);
                    }
                });
    }
}


你可能感兴趣的:(Android)