okhttp同步/异步

public class MainActivity extends AppCompatActivity {
    private OkHttpClient okHttpClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        okHttpClient = App.okHttpClient();
    }
    //同步的get
    public void get(View view) {
        //request 设置url
        final Request request= new Request.Builder()
                .url("http://www.baidu.com")
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //通过newCall方法将request转换成call ,如果用execute()是同步执行
                    Response execute = okHttpClient.newCall(request).execute();
                    if (execute.isSuccessful()){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,"get成功",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,"get失败",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //异步get,所以的回调方法里面都是分线程.不能更新ui
    public void getAsync(View view) {
        final Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .build();
        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()){
                    String json = response.body().toString();
                    //Gson解析
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "get成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                }else {
                    //Gson解析
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "getshibai", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }
    //Post异步请求
    public void postAsync(View view) {
        FormBody formBody = new FormBody.Builder()
                .add("type", "yuantong")
                .add("postid", "1111111")
                .build();
        Request request = new Request.Builder()
                .url(" http://www.kuaidi100.com/query")
                .post(formBody)
                .build();
        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()){
                    String json = response.body().toString();
                    //Gson解析
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "post成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                }else {
                    //Gson解析
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "getshibai", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
            }
        }
Myapp:
public class App extends Application {

    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,可以通过拦截器打印日志
    private class MyLogInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
         Request request = chain.request().newBuilder()
                    .header("shenfen", "chinesse")
                    .build();
            HttpUrl url = request.url();
            String httpUrl = url.url().toString();
            Log.e("TAG", "============" + httpUrl);
            Response response = chain.proceed(request);
            int code = response.code();
            Log.e("TAG", "============response.code() == " + code);
            return response;
    }
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值