[英]How to send JSON and an Image in same POST request and cascade it? Spring Boot
[英]How to send image with post request
我需要使用诸如key = value之类的格式发送数据的发布请求,而我正在那样工作(url是ws的url,这是可以的)
HttpEntityEnclosingRequestBase post=new HttpPost();
String result = "";
HttpClient httpclient = new DefaultHttpClient();
post.setURI(URI.create(url));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
for (Entry<String, String> arg : args.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(arg.getKey(), arg
.getValue()));
}
http.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = getStringFromStream(instream);
instream.close();
}
return result;
发送String数据时可以。 我的问题是,当一个参数是图片而其他参数是字符串时,该如何修改?
当您使用多种数据类型通过HttpClient发送时,必须使用MultipartEntityBuilder(org.apache.http.entity.mime中的类)
试试这个
MultipartEntityBuilder s= MultipartEntityBuilder.create();
File file = new File("sample.jpeg");
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, "sample.jpeg");
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
}
如果您希望将图像作为帖子请求的数据部分发送,则可以单击评论中发布的某些链接。
如果图像/二进制数据必须绝对是标头(我不建议这样做),则应在Base64 Android类内部使用encodeToString方法。 我不建议在大型图像中使用此方法,因为您需要将整个图像作为字节数组加载到内存中,然后才能将其转换为字符串。 将其转换为字符串后,其大小也将变为以前的大小的4/3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.