okhttp3在Fragment中的使用

由于okhttp3的异步请求,需要开启线程,之前在activity中都是直接调用UI线程,可是发现在fragment中不行,现在记录下代码:

 

//上传文件
MultipartBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        // .addFormDataPart("name", "庄贺文")
        .addFormDataPart("user_id", ""+user_id)
        .addFormDataPart("token", token)
        .addFormDataPart("file1", "file1.jpg", RequestBody.create(MediaType.parse("application/octet-stream"), file1))
        .addFormDataPart("file2", "file2.jpg", RequestBody.create(MediaType.parse("application/octet-stream"), file2))
        .addFormDataPart("file3", "file3.jpg", RequestBody.create(MediaType.parse("application/octet-stream"), file3))
         .build();
String url = ConstantsUrl.OWNERAPPLY_URL;
Request request =
        new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

// 3、将request封装为call,是单个请求的执行者
Call call = client.newCall(request);
// 4、执行call(异步和同步)
// call.execute();
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e("111", "服务器未连接");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        //得到服务器返回的具体内容
        final String res = response.body().string();
        Log.e("服务器发送数据", res);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = null;
                switch (res) {
                    case "上传成功":
                        Toast.makeText(OwnerApplyActivity.this, "上传成功,等待审核通过", Toast.LENGTH_SHORT)
                                .show();
                        intent = new Intent(OwnerApplyActivity.this, MainActivity.class);
                        startActivity(intent);
                        break;

                    default:
                        Toast.makeText(OwnerApplyActivity.this, "上传失败", Toast.LENGTH_SHORT)
                                .show();

                        break;
                }
            }
        });
    }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值