【发布时间】:2016-06-08 02:49:32
【问题描述】:
由于 Android 开发人员删除了 Apache HTTP 客户端,我正在转向 HttpURLConnection。我能够重写我的所有功能,除了一个。 我正在发送带有名称和日期的字节数组(图像)。实际上我的功能允许一次发送许多图像,但我只发送一个。 到目前为止,我一直在使用 MultipartEntityBuilder 构建 HttpEntity 并通过 httpPost.setEntity(entity) 设置它。但是我想摆脱 MultipartEntityBuilder。
现在我有以下代码 sn-p:
public void sendImage(URL url, byte[] image, String name, long date) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addBinaryBody("file[]", image);
entityBuilder.addTextBody("file_name[]", name);
entityBuilder.addTextBody("file_size[]", String.valueOf(date));
HttpEntity entity = entityBuilder.build();
conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
entity.writeTo(os);
os.close();
conn.connect();
// read response code
}
在服务器端我可以接收这样的数据:
$file = $_POST['file'];
$file_name = $_POST['file_name'];
$file_size = $_POST['file_size'];
我无法更改服务器实现。
我尝试了这个线程的解决方案: Sending files using POST with HttpURLConnection 但我不知道如何将其调整到我的服务器。
有没有办法摆脱 HttpEntity?我现在不想使用其他库(Volley、OkHttp 或 Retrofit)。将来我可能会搬到其中之一。
感谢您的帮助。
【问题讨论】:
标签: android http http-post httpurlconnection