我想构建一个包含以下参数的多部分请求:名称(字符串)、电子邮件(字符串)和文件上传(文件)。我正在使用下面的 Java 代码(在 Android 中工作)。
httppost.getRequestLine() 输出
POST http://www.myurl.com/upload HTTP/1.1
所以客户端站点上的一切看起来都不错,但我的服务器 (Django/Apache) 将其作为 GET 请求读取,没有 GET 参数 - request.method
生成“GET”, request.GET.items()
生成一个空字典。
我做错了什么?我实际上不知道如何正确设置多部分参数——我在猜测——所以这可能就是问题所在。
public void SendMultipartFile() {
Log.e(LOG_TAG, "SendMultipartFile");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myurl.com/upload");
File file = new File(Environment.getExternalStorageDirectory(),
"video.3gp");
Log.e(LOG_TAG, "setting up multipart entity");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("fileupload", cbFile);
Log.i("SendLargeFile", "file length = " + file.length());
try {
mpEntity.addPart("name", new StringBody(name));
mpEntity.addPart("email", new StringBody(email));;
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
Log.e(LOG_TAG, "UnsupportedEncodingException");
e1.printStackTrace();
}
httppost.setEntity(mpEntity);
Log.e(LOG_TAG, "executing request " + httppost.getRequestLine());
HttpResponse response;
try {
Log.e(LOG_TAG, "about to execute");
response = httpclient.execute(httppost);
Log.e(LOG_TAG, "executed");
HttpEntity resEntity = response.getEntity();
Log.e(LOG_TAG, response.getStatusLine().toString());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
最佳答案
您可能找错地方了。您正在发布,但在请求中查找数据。GET:
尝试在“request.POST”和“request.FILES”中查找 QueryDict...
http://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.FILES
关于android - 使用 MultipartEntity 构建 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2607020/