OkHttpClient请求数据

//OKHttp请求依赖 compile 'com.squareup.okhttp3:okhttp:3.9.0'

 

public class App extends Application {


    //OkHttpClient实例是唯一的, 所有的请求都会通过这个OkHttpClient,所以所有的请求都可能被拦截器拦截,
    // 我们可以在这个必经之路,做一些通用的操作,比如打印日志.
    private static OkHttpClient okHttpClient;

    @Override
    public void onCreate() {
        super.onCreate();
        //建议一个app只有一个OkHttpClient实例
        okHttpClient = new OkHttpClient();
        okHttpClient = okHttpClient.newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new MyLogInterceptor())//拦截器
                .build();
    }

    public static OkHttpClient okHttpClient() {
        return okHttpClient;
    }


    //拦截器,可以修改header,可以通过拦截器打印日志
    public class MyLogInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder()
                    .header("shenfenyanzheng", "zhangsan")
                    .build();
            HttpUrl url = request.url();
            String httpUrl = url.url().toString();
            Response response = chain.proceed(request);
            int code = response.code();
            return response;
        }
    }
}

 

//在方法中使用
 
//异步,所以的回调方法里面都是分线程.不能更新ui  //request 设置url  Request request = new Request.Builder() .url("http://www.baidu.com") .build();  App.okHttpClient().newCall(request).enqueue(new Callback() { @Override  public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override  public void run() { Toast.makeText(MainActivity.this, "get失败", Toast.LENGTH_SHORT).show();  } });  } @Override  public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { //得到Json串  String json = response.body().string();  //用Gson解析  runOnUiThread(new Runnable() { @Override  public void run() { Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();  } });  } else { //提示用户  runOnUiThread(new Runnable() { @Override  public void run() { Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();  } });  } } });

你可能感兴趣的:(Android)