由于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;
}
}
});
}
});