关于Okhttp3api使用

Posted Red风信子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Okhttp3api使用相关的知识,希望对你有一定的参考价值。

简介

Okhttp是square公司推出的一款android和Java网络请求库,当前推出了Okhttp3,在原来的基础上做了很大改进,也是Android目前最流行的网络库之一,本系列文章就是基于最新的来剖析。鉴于能力以及代码的优化改动,文中如有不足之处还望指教,谢谢。

api使用

Android使用注意申请网络权限,同时不能在主线程请求

同步请求execute

private static void executeRequest() throws Exception 
        OkHttpClient client = new OkHttpClient();
    
        // Create request for remote resource.
        Request request = new Request.Builder()
                .url(ENDPOINT)
                .build();
    
        // Execute the request and retrieve the response.
        try (Response response = client.newCall(request).execute()) 
          // Deserialize HTTP response to concrete type.
          ResponseBody body = response.body();
          List<Contributor> contributors = CONTRIBUTORS_JSON_ADAPTER.fromJson(body.source());
    
          // Sort list by the most contributions.
          Collections.sort(contributors, (c1, c2) -> c2.contributions - c1.contributions);
    
          // Output list of contributors.
          for (Contributor contributor : contributors) 
            System.out.println(contributor.login + ": " + contributor.contributions);
          
        
    

异步请求enqueue

private static void enqueueRequest() throws Exception 
        OkHttpClient client = new OkHttpClient();

        // Create request for remote resource.
        Request request = new Request.Builder()
                .url(ENDPOINT)
                .build();

        client.newCall(request).enqueue(new Callback() 
          @Override
          public void onFailure(Call call, IOException e) 
            System.out.println("onFailure e=" + e);
          

          @Override
          public void onResponse(Call call, Response response) throws IOException 
            boolean isSuccess = response.isSuccessful();
            int code = response.code();
            String json = response.body().string();
            System.out.println("onResponse isSuccess=" + isSuccess + ", code="+code+", json="+json);
            if(response.isSuccessful())

            
          
        );
    

使用header

private static void headerRequest() throws Exception 
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(ENDPOINT)
                .addHeader("User-Agent","from nate http")
                //.addHeader("Accept","text/plain,text/html")
                .build();

        client.newCall(request).enqueue(new Callback() 
          @Override
          public void onFailure(Call call, IOException e) 
            System.out.println("onFailure e=" + e);
          

          @Override
          public void onResponse(Call call, Response response) throws IOException 
            boolean isSuccess = response.isSuccessful();
            int code = response.code();
            String json = response.body().string();
            System.out.println("onResponse isSuccess=" + isSuccess + ", code="+code+", json="+json);
            if(response.isSuccessful())
              Headers headers = response.headers();
              for(int i=0;i<headers.size();i++)
                System.out.println("onResponse name=" + headers.name(i)+", value="+headers.value(i));
              
            
          
        );
    

HttpUrl自动封装参数(get类型参数)

private static void getParamsRequest() throws Exception 
        OkHttpClient client = new OkHttpClient();

        HttpUrl httpUrl = HttpUrl.parse("https://api.heweather.com/x3/weather")
                .newBuilder()
                .addQueryParameter("city","beijing")
                .addQueryParameter("key", "d17ce22ec5404ed883e1cfcaca0ecaa7")
                .build();
        String url = httpUrl.toString();
        //url=https://api.heweather.com/x3/weather?city=beijing&key=d17ce22ec5404ed883e1cfcaca0ecaa7
        System.out.println("url=" + url);

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

        client.newCall(request).enqueue(new Callback() 
          @Override
          public void onFailure(Call call, IOException e) 
            System.out.println("onFailure e=" + e);
          

          @Override
          public void onResponse(Call call, Response response) throws IOException 
            boolean isSuccess = response.isSuccessful();
            int code = response.code();
            String json = response.body().string();
            System.out.println("onResponse isSuccess=" + isSuccess + ", code="+code+", json="+json);
            if(response.isSuccessful())

            
          
        );
    

get请求

/**
* OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor() //请求前的拦截器
.addNetworkInterceptor() // 网络拦截器
.cache() // 缓存目录
.connectTimeout() // 连接超时
.cookieJar() // cookie的读取,保存,需要自己实现
.sslSocketFactory() // https证书
...略...
.build();
*/
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException 
// 2. 创建一个request,包含请求地址、请求参数、请求头等
Request request = new Request.Builder()
.url(url)
.build();
// 3. 同步请求,得到响应
Response response = client.newCall(request).execute();
return response.body().string();

post请求

private static void postParamsRequest() throws Exception 
        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder().add("username", "nate")
                .add("userage", "99").build();
        Request request = new Request.Builder()
                .url(ENDPOINT)
                .post(body)
                .build();
        try 
            Response response = client.newCall(request).execute();
            System.out.println("response=" + response.body().string());
            if (response.isSuccessful()) 

            
         catch (IOException e) 
            e.printStackTrace();
        
    
// 1.创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
// 2.创建请求参数,注意,此处有多种方式
RequestBody requestBody = new FormBody.Builder()
.add("param", "value")
.build();
// 3.创建请求request
Request request = new Request.Builder()
.url("https://wwww.xxx.com")
.post(requestBody)
.build();
// 4.发起请求,此处使用的是异步请求,按需要选择同步或异步
okHttpClient.newCall(request)
.enqueue(new Callback() 
	@Override
	public void onFailure(Call call, IOException e) 
	
	@Override
	public void onResponse(Call call, Response response) throws IOException 
		// 5.处理相响应
	
);

文件上传

上传文件本质上是post请求,区别是在参数类型上

不要忘记权限,6.0(api23)动态权限

 private static void uploadRequest() throws Exception 
        RequestBody imageBody = RequestBody.create(MediaType.parse("image/jpeg"), new File("/Users/nate/girl.jpg"));
        MultipartBody body = new MultipartBody.Builder().
                setType(MultipartBody.FORM).
                addFormDataPart("name", "nate").
                addFormDataPart("filename", "girl.jpg", imageBody).build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.1.6:8080/web/UploadServlet")
                .post(body)
                .build();
        try 
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());
            if (response.isSuccessful()) 

            
         catch (IOException e) 
            e.printStackTrace();
        
    
// 1.创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
// 不同点
// 2.创建请求参数,设置对应的参数类型即可
RequestBody requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), new File("xxx.txt"));
// 3.创建请求request
Request request = new Request.Builder()
.url("https://wwww.xxx.com")
.post(requestBody)
.build();
// 4.发起请求
okHttpClient.newCall(request)
.enqueue(new Callback() 
	@Override
	public void onFailure(Call call, IOException e) 
	
	@Override
	public void onResponse(Call call, Response response) throws IOException 
	// 5.处理相响应
	
);

Multipart文件

multipart文件同上传文件,区别是它可以同时有字符参数,也可以有文件

// 1.创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
// 不同点
// 2.创建请求参数,设置对应的参数类型即可
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("fileParam", "xxx.png", RequestBody.create(MediaType.parse("image/png"), new File("xxx/xxx.png")))
.addFormDataPart("param", "value")
.build();
// 3.创建请求request
Request request = new Request.Builder()
.url("https://wwww.xxx.com")
.post(requestBody)
.build();
// 4.发起请求
okHttpClient.newCall(request)
.enqueue(new Callback() 
	@Override
	public void onFailure(Call call, IOException e) 
	
	@Override
	public void onResponse(Call call, Response response) throws IOException 
	// 5.处理相响应
	
);

cache

Okhttp仅支持get请求缓存哦,其他请求方式需要自己实现

private static void cacheRequest() throws Exception 
        int maxCacheSize = 10 * 1024 * 1024;

        Cache cache = new Cache(new File("/home/dunn/project/github/Okhttp3.14.x/okhttp/cache/test/source"), maxCacheSize);
        OkHttpClient client = new OkHttpClient.Builder().cache(cache).build();

        Request request = new Request.Builder().url("http://www.qq.com/").
                cacheControl(new CacheControl.Builder().maxStale(365, TimeUnit.DAYS).build()).
                build();

        Response response = client.newCall(request).execute();


        String body1 = response.body().string();
        System.out.println("network response " + response.networkResponse());
        System.out.println("cache response " + response.cacheResponse());

        System.out.println("**************************");

        Response response1 = client.newCall(request).execute();

        String body2 = response1.body().string();
        System.out.println("network response " + response1.networkResponse());
        System.out.println("cache response " + response1.cacheResponse());
    
OkHttpClient okHttpClient = new OkHttpClient.Builder()
// 大小是bytes
.cache(new Cache(new File("xx/xxx/"), 20 * 1024))
.build();

超时

okhttp超时分为连接超时、读取超时、写入超时

OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.pingInterval(10, TimeUnit.SECONDS) // websocket 轮训间隔

以上是关于关于Okhttp3api使用的主要内容,如果未能解决你的问题,请参考以下文章

ES6学习:两个面试题目--关于模板字符串

关于聚类方法的问题

Apple官文中的KVO 与 FBKVOController

在推文中查找表情符号作为整个集群而不是单个字符

关于DH和RSA算法的简单比较

跨域问题--自整理