我想将一些文字和图片发送到服务器。我为此目的使用MultipartEntityBuilder
。但是从API 22开始HttpEntity
被折旧。那么,我该如何将我的多部分添加到HttpURLConnection
?
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setCharset(MIME.UTF8_CHARSET);
multipartEntityBuilder.addTextBody("fname", fname, ContentType.create("text/plain", MIME.UTF8_CHARSET));
.
.
.
multipartEntityBuilder.addTextBody("admin_id", adminDataListener.getAdminId(),
ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (imageAttached){
multipartEntityBuilder.addTextBody("existing_image", adminDataListener.getAdminId(),
ContentType.create("text/plain", MIME.UTF8_CHARSET));
multipartEntityBuilder.addBinaryBody("image1 ", newImageFile, ContentType.MULTIPART_FORM_DATA,
newImageFile.getName());
} else {
multipartEntityBuilder.addTextBody("existing_image", adminDataListener.getAdminImage(),
ContentType.create("text/plain", MIME.UTF8_CHARSET));
}
答案 0 :(得分:-2)
您必须定义边界并使用它构建多部分有效负载。
String boundary = "-----stackoverflow--------" + System.currentTimeMillis();
multipartEntityBuilder.setBoundary(boundary);
然后你应该通过以下方式告诉服务器使用的边界:
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
最后构建一个HttpEntry并让它将其内容写入输出流
HttpEntity entity = multipartEntityBuilder.build();
entity.writeTo(conn.getOutputStream());
以通常的方式获取响应代码并返回页面。