使用MultipartEntity帮助构建POST请求(新手问题)

时间:2010-04-09 11:36:51

标签: android django file-upload httpclient multipart

我想使用以下参数构造一个多部分请求:name(字符串),email(字符串)和fileupload(file)。我正在使用下面的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();
  }
 }

2 个答案:

答案 0 :(得分:0)

似乎你看错了地方。你正在发帖,但在request.GET中寻找数据:

尝试在“request.POST”和“request.FILES”中查找QueryDict ...

http://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.FILES

答案 1 :(得分:0)

我遇到了与MultipartEntity请求相同的问题。我需要将图像上传到服务器。 所以我通过HttpURLConnection类做了MultipartEntity请求。 我把我的代码放在这里,认为它对你有用。 您需要设置URL路径和文件路径。对于这个使用方法put。

public class UploadImage
implements Runnable{

private static String delimiter = "--";
private static String boundary = "SwA" + Long.toString(System.currentTimeMillis()) + "SwA";
private static int bytesRead;
private static int bytesAvailable;
private static int bufferSize;
private static byte[] buffer;
private static int maxBufferSize = 1 * 1024 * 1024;

private String URL;
private String file;


@Override
public void run()
{
    HttpURLConnection conn = null;
    String response = null;
    try {

        URL url = new URL(URL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("USER-AUTH", UserPreferences.getToken());
        conn.connect();
        //

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes((delimiter + boundary + "\r\n"));
        dos.writeBytes("Content-Disposition: form-data; name=\"" + "image" + "\"; filename=\"" + file + "\"\r\n");
        dos.writeBytes("Content-Type: mimetype\r\n");// Content-Type:
                                                     // text/plain
        dos.writeBytes("Content-Transfer-Encoding: binary\r\n\r\n");


        // create a buffer of maximum size
        FileInputStream fileInputStream = new FileInputStream(new File(file));
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        dos.writeBytes("\r\n");
        dos.writeBytes(delimiter + boundary + delimiter + "\r\n");
        fileInputStream.close();
        dos.flush();
        dos.close();
        int responseCode = conn.getResponseCode();

        if (responseCode != 200) {
            throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
        }

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int bytesRead;
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();

        is.close();
        response = new String(bytesReceived);


    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

public void put(String targetURL, String file)
{
    this.URL = targetURL;
    this.file = file;
}}