Android 网络编程之最新OKHTTP:3.9.0

 

本节前言

本来是想围绕着HttpClient讲解的,后来发先Android4.4之后okhttp代替了hc,所以将不再讲解hc

okhttp的简单使用,主要包含:

  • 一般的get请求
  • 一般的post请求
  • 基于Http的文件上传
  • 文件下载
  • 加载图片
  • 支持请求回调,直接返回对象、对象集合
  • 支持session的保持

使用okhttp

使用okhttp前首先要添加依赖

compile 'com.squareup.okhttp3:okhttp:3.9.0'

一般的get请求

对了网络加载库,那么最常见的肯定就是http get请求了,比如获取一个网页的内容

OkHttpClient client = new OkHttpClient();

  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  String string = response.body().string();
  System.out.println(string);
}

运行结果

 
  • 以上就是发送一个get请求的步骤,首先构造一个Request对象,参数最起码有个url,当然你可以通过Request.Builder设置更多的参数比如:header、method等。

  • 然后通过request的对象去构造得到一个Call对象,类似于将你的请求封装成了任务,既然是任务,就会有execute()和cancel()等方法。

  • 最后,我们希望以异步的方式去执行请求,所以我们调用的是call.enqueue,将call加入调度队列,然后等待任务执行完成,我们在Callback中即可得到结果。

  • onResponse回调的参数是response,一般情况下,比如我们希望获得返回的字符串,可以通过response.body().string()获取;如果希望获得返回的二进制字节数组,则调用response.body().bytes();如果你想拿到返回的inputStream,则调用response.body().byteStream()

一般的post请求

1) POST提交键值对

很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来做这件事情。比如提交用户名和密码用来登录

post提交键值对其实和get方法之多了一个RequestBody,用来添加键值对

get提交连接如下

http://192.168.56.1:8080/LoginServlet?username=abc&password=123

post提交连接如下

OkHttpClient client = new OkHttpClient();
RequestBody requestBody=new FormBody.Builder()
                    .add("username","abc")
                    .add("password","123")
                    .build();
  Request request = new Request.Builder()
      .url(url)
      .post(requestBody)
      .build();

  Response response = client.newCall(request).execute();
  String string = response.body().string();
  System.out.println(string);
}

是不是比hc简单多了,这里需要注意到一点是最新版的okhttp,原来的FormEncodingBuilder被FormBody代替了

POST提交Json数据

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    
     OkHttpClient client = new OkHttpClient();
     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();
   

下载文件

 new Thread(){public void run(){
            OkHttpClient client = new OkHttpClient();

            Request request=new Request.Builder().url("http://192.168.56.1:8080/tomcat.png").build();
            try {
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("下载失败");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        InputStream in=response.body().byteStream();
                        FileOutputStream fos=new FileOutputStream(new File(getFilesDir(),"11.png"));
                        int len=0;
                        byte []bytes=new byte[1024];
                        while ((len=in.read(bytes))!=-1){
                            fos.write(bytes,0,len);
                        }
                        fos.flush();

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }}.start();

其实仔细看还是和上面的get请求差不多,无非就是get下载了,这里就只是改变了

       Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //连接失败
                         }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //连接成功
                        }

上传文件

public static void doFile(String url, String pathName, String fileName, Callback callback) {
    //判断文件类型
    MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName));
    //创建文件参数
    MultipartBody.Builder builder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(MEDIA_TYPE.type(), fileName,
                    RequestBody.create(MEDIA_TYPE, new File(pathName)));
    //发出请求参数
    Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + "9199fdef135c122")
            .url(url)
            .post(builder.build())
            .build();
    Call call = getInstance().newCall(request);
    call.enqueue(callback);
}

/**
 * 根据文件路径判断MediaType
 *
 * @param path
 * @return
 */
private static String judgeType(String path) {
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String contentTypeFor = fileNameMap.getContentTypeFor(path);
    if (contentTypeFor == null) {
        contentTypeFor = "application/octet-stream";
    }
    return contentTypeFor;
}
原文地址:https://www.cnblogs.com/xgjblog/p/10567681.html