android中okhttp的使用

1.1 okhttp简介(原生)

OKHttp是一款高效的HTTP客户端,支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,还有透明的GZIP压缩,请求缓存等优势,其核心主要有路由、连接协议、拦截器、代理、安全性认证、连接池以及网络适配,拦截器主要是指添加,移除或者转换请求或者回应的头部信息

这个库也是square开源的一个网络请求库(okhttp内部依赖okio)。现在已被Google使用在Android源码上了,可见其强大。

关于网络请求库,现在应该还有很多人在使用android-async-http。他内部使用的是HttpClient,但是Google在6.0版本里面删除了HttpClient相关API,可见这个库现在有点过时了。


1.2 下载地址 

http://square.github.io/okhttp/

1.3 OKHTTP 主要功能

1、联网请求文本数据
2、大文件下载
3、大文件上传
4、请求图片


1.4 在lib下加入jar  okhttp-3.4.1.jar    okio-1.9.0.jar 

1.5 案例:

get方式  记得添加联网权限

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

post方式

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

OkHttpClient client = new OkHttpClient();

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

联网的操作应该在子线程中操作,handler发送消息



2.第三方封装好的OKHttp库-okhttp-utils

2.1 https://github.com/hongyangAndroid/okhttp-utils

2.2 使用okhttp-utils请求文本

get


public void getDataByOkhttputils()
{
    String url = "http://www.zhiyun-tech.com/App/Rider-M/changelog-zh.txt";
    url="http://api.m.mtime.cn/PageSubArea/TrailerList.api";
    OkHttpUtils
            .get()
            .url(url)
            .id(100)
            .build()
            .execute(new MyStringCallback());
}

post

public void getDataByOkhttputils()
{
    String url = "http://www.zhiyun-tech.com/App/Rider-M/changelog-zh.txt";
    url="http://api.m.mtime.cn/PageSubArea/TrailerList.api";
    OkHttpUtils
            .get()
            .url(url)
            .id(100)
            .build()
            .execute(new MyStringCallback());
}

2.3 文件下载

public void downloadFile()
{
   
String url = "http://vfx.mtime.cn/Video/2016/07/24/mp4/160724154733643806.mp4";
   
OkHttpUtils//
           
.get()//
           
.url(url)//
           
.build()//
           
.execute(new 

FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "160724154733643806.mp4")//
            {

                @Override
                public void onBefore(Request request, int id) {
                }

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

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

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

记得加上权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2.4文件上传

public void multiFileUpload()
{
    String mBaseUrl = "http://192.168.10.165:8080/FileUpload/FileUploadServlet";
    File file = new File(Environment.getExternalStorageDirectory(), "1.jpg");
    File file2 = new File(Environment.getExternalStorageDirectory(), "1.txt");
    if (!file.exists())
    {
        Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();
        return;
    }
    Map<String, String> params = new HashMap<>();
    params.put("username", "杨光福");
    params.put("password", "123");

    String url = mBaseUrl;
    OkHttpUtils.post()//
            .addFile("mFile", "messenger_01.png", file)//
            .addFile("mFile", "test1.txt", file2)//
            .url(url)
            .params(params)//
            .build()//
            .execute(new MyStringCallback());
}

2.5 请求图片


public void getImage(View view) {
    mTv.setText("");
    String url = "http://images.csdn.net/20150817/1.jpg";
    OkHttpUtils
            .get()//
            .url(url)//
            .tag(this)//
            .build()//
            .connTimeOut(20000)
            .readTimeOut(20000)
            .writeTimeOut(20000)
            .execute(new BitmapCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    mTv.setText("onError:" + e.getMessage());
                }

                @Override
                public void onResponse(Bitmap bitmap, int id) {
                    Log.e("TAG", "onResponsecomplete");
                    mImageView.setImageBitmap(bitmap);
                }
            });
}

2.6 缓存数据

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();
        Log.e("TAG", "onError:" + e.getMessage());
   
}

    @Override
   
public void onResponse(String response, int id) {
       
Log.e("TAG", "onResponsecomplete");

       
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;
           
case 108://列表中显示数据
               
if (response != null) {
                   
//缓存数据
                  
 
CacheUtils.putString(OKHttpActivity.this, url, response);
                   
//解析和显示数据
                   
processData(response);









猜你喜欢

转载自blog.csdn.net/sinat_26397681/article/details/52794433