之所以想记录下来,主要是之前对这个不太熟,然后在网上找了大半天也没找到合适的,然后自己慢慢试了出来,比较囧。。。但分享给大家,亲测可用!
主要分为两步:
1. 将图片url转为二进制字符串;
2. 将二进制字符串以及其他字段一并上传。
直接上代码:
public class HttpClient {
public static final OkHttpClient client =
new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();
public static String getResponse(String url, String imgUrl) throws IOException {
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), getFile(imgUrl));
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("param1", param1)
.addFormDataPart("param2", param2)
.addFormDataPart("image", "image", fileBody)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new RuntimeException(response.body().string());
}
}
private static byte[] getFile(String imgUrl) throws IOException {
Request request = new Request.Builder()
.url(imgUrl)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().bytes();
} else {
throw new RuntimeException(response);
}
}
}
其中OkHttpClient包请自行导入。