OKhttp的使用

1.初始化方式

   //1.创建一个OKHttpClient实例
        //老版本创建OkHttpClient的方式
        client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

2.同步请求

    public void btnClick(View view) {
        //2.创建一个请求
        final Request request = new Request.Builder()
                //设置请求地址
                .url("http://www.baidu.com")
                //设置请求方式为Get请求,默认即此
                .get()
                .build();
        Runnable runnable = new Runnable() {
            public void run() {
                //3.发起网络请求
                Call call = client.newCall(request);
                try {
                    //发起同步网络请求
                    Response response = call.execute();
                    String result = response.body().string();
                    Log.d("google_lenve_fb", "btnClick: " + result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();
    }
3.异步请求

  public void btnClick2(View view) {
        Request request = new Request.Builder()
                //如果使用自带的模拟器10.0.2.2
                .url("http://10.3.134.6:8080/sz1605/OKHttpTest?username=张三&password=123456")
                .build();
        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 {
                //如果请求成功
                if (response.isSuccessful()) {
                    //response.body().string()获取请求的字符串
                    Log.d("google_lenve_fb", "onResponse: " + response.body());
                    //获取头信息
                    Headers headers = response.headers();
                    Set<String> names = headers.names();
                    Iterator<String> iterator = names.iterator();
                    while (iterator.hasNext()) {
                        String name = iterator.next();
                        Log.d("google_lenve_fb", "onResponse: name:" + name + ";value:" + headers.get(name));
                    }
                }
            }
        });
    }

3.表单请求

   public void btnClick3(View view) {
        //通过表单来传递参数
        FormBody formbody = new FormBody.Builder()
                .add("password", "66666")
                .add("username", "李四").build();
        Request request = new Request.Builder()
                .post(formbody)
                .url("http://10.3.134.6:8080/sz1605/OKHttpTest").build();
        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 {
                Log.d("google_lenve_fb", "onResponse: 请求成功!");
            }
        });
    }
4.传送数据

 public void btnClick4(View view) {
        //通过流的方式传递参数
        JSONObject jsonStr = new JSONObject();
        try {
            jsonStr.put("username", "王五");
            jsonStr.put("password", "333333");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType jsonMediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody jsonBody = RequestBody.create(jsonMediaType,jsonStr.toString());
        Request request = new Request.Builder()
                .post(jsonBody)
                .url("http://10.3.134.6:8080/sz1605/OKHttpTest").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }

5.传送文件

    public void pushImage(View view) {
        MediaType fileMediaType = MediaType.parse("application/octet-stream");
        File imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "p2.png");
        RequestBody fileBody = RequestBody.create(fileMediaType, imageFile);
        Request request = new Request.Builder()
                .post(fileBody)
                .url("http://10.3.134.6:8080/sz1605/OKHttpTest").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("google_lenve_fb", "onResponse: 文件上传成功!");
            }
        });
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值