OKHttp文件上传

/**
 *
 * @param url  上传文件地址
 * @param map  上传的参数
 * @param file 上传的文件
 * @return
 * @throws IOException
 */
public static Response okhttpUpload(final String url, final Map map, File file)
        throws IOException {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    builder.setType(MultipartBody.FORM);
    if (file != null) {
        builder.addFormDataPart("file", file.getName(),
                RequestBody.create(MediaType.parse("multipart/form-data"), file));
    }
    if (map != null) {
        // map 里面是请求中所需要的 key 和 value
        for (Map.Entry entry : map.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }
    }
    RequestBody body = builder.build();
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    OkHttpClient okHttpClient = new OkHttpClient();
    Response response = okHttpClient.newCall(request).execute();
    return response;
}

你可能感兴趣的:(android,工具,java,android)