okhttp

​ 使用前准备工作:

implementation implementation 'com.squareup.okhttp3:okhttp:3.2.0'
implementation 'com.squareup.okio:okio:1.7.0'

用法

1.get用法

  1. 要有一个客户端,类似于要有一个浏览器

    OkHttpClient client = OkHttpClient client = new OkHttpClient.Builder()
    		.connecTimeout(10000,TimeUnit.MILLSECONDS)
    		.build();
  2. 创建请求内容

    Request request = new Request request = new Request()
    		.get()
    		.url(BASE_URL + "/get/text")
    		.build();
  3. 用client去创建请求任务

    Call call = client.newCall(request);
  4. 异步请求

    callcall.enqueue(new Callback(){
    	@Override
    	public void onFaile(Call call,IOException e){
    	
    	}
    	@Override
    	public void onResponse(Call call,Response response) throws IOException{
    	
    	}
    
    });
    //注意的是onResponse回调并非在UI线程
       
    5. 同步请求调用Call的execute方法
    
    6. 基本步骤总结:创建OkHttpClient、Request和Call,最后调用Call的enqueue()方法.
    
    ### 2.post请求
    
    
    
    ### 3.异步下载文件
    
    ### 4.异步上传Multipart文件
    
    ### 5.拦截器
    
    #### 5.1HttpLoggingInterceptor用法

    //1.定义拦截器 + Logger

private static HttpLoggingInterceptor sInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
try {
String text = URLDecoder.decode(message, “utf-8”);
Log.e(“OKHttp—–”, text);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e(“OKHttp—–”, message);
}
}
});
//2.设置打印级别
//3.给client添加拦截器
sInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(sInterceptor)
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();


#### 5.2应用场景

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!