【发布时间】:2015-08-16 08:29:19
【问题描述】:
我有一个 android 应用程序,它使用来自 apache httpcomponents 的多方。该应用程序使用 HTTP 请求将文件上传到 php 脚本。但是,我上传的文件 (.ogg) 以 $_POST 而不是 $_FILES 结尾,它看起来像二进制文件,尽管我可能是错误的。
我有 chrome rest 扩展,我用它来发布一个包含完全相同的 .ogg 文件的 multipart/form-data 请求,并且文件最终出现在正确的位置 ($_FILES)。
Android代码如下:
// Send the file to the server.
// Create HTTP objects.
// Request.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ACTION);
// Response.
HttpResponse httpResponse;
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(mediaFile, "audio/ogg");
mpEntity.addPart("file", cbFile);
httpPost.setEntity(mpEntity);
// Execute.
httpResponse = httpClient.execute(httpPost);
// Evaluate the response.
int statusCode = httpResponse.getStatusLine().getStatusCode();
// Make sure everythings okay.
if (statusCode == 200) {
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
String body = EntityUtils.toString(resEntity);
resEntity.consumeContent();
Log.d("APP_STATUS", body);
}
}
httpClient.getConnectionManager().shutdown();
还有非常简单的 PHP 脚本:
<?php
echo "\$_POST";
var_dump($_POST);
echo "\$_FILES";
var_dump($_FILES);
?>
使用应用时的响应:
使用 Chrome REST 扩展时的响应:
如果有人对我的失败之处有任何见解,请告诉我。
【问题讨论】:
-
你可以访问
MultipartEntityBuilder吗? -
我相信是的,我使用的代码来自类似情况,只是他们正在上传图像文件。
标签: php android multipartentity