我想用下面的參數構造一個多部分請求:name(字符串),email(字符串)和fileupload(文件)。我正在使用下面的Java代碼(在Android中工作)。幫助構建一個帶有MultipartEntity的POST請求(新手問題)
的httppost.getRequestLine()打印
POST http://www.myurl.com/upload HTTP/1.1
所以一切看起來都在客戶端站點不錯,但我的服務器(Django的/阿帕奇),把它讀成一個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();
}
}
請看一看這個以前回答問題 http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk – Omie 2012-09-30 10:48:28