android okHttp3 post上传图片给服务器

 
  

进行post请求

OkHttpClient client = new OkHttpClient();
// form 表单形式上传
MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
if(file != null){
    // MediaType.parse() 里面是上传的文件类型。
    RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
    String filename = file.getName();
    // 参数分别为, 请求key ,文件名称 , RequestBody
    requestBody.addFormDataPart("file", filename, body).addFormDataPart("uid", String.valueOf(uid));
}

Request request = new Request.Builder().url(API.UpImg).post(requestBody.build()).build();
// readTimeout("请求超时时间" , 时间单位);
client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String string = response.body().string();
        Message message = new Message();
        message.what = 0;
        message.obj = string;
        handler.sendMessage(message);
    }
});

你可能感兴趣的:(android okHttp3 post上传图片给服务器)