2010-04-09 8 views
5

Me gustaría construir una solicitud multiparte, con los siguientes parámetros: nombre (cadena), correo electrónico (cadena) y carga de archivo (archivo). Estoy usando el código de Java a continuación (trabajando en Android).Ayuda para construir una solicitud POST con MultipartEntity (pregunta de novato)

El httppost.getRequestLine() imprime

POST http://www.myurl.com/upload HTTP/1.1 

Así que todo se ve bien en el sitio del cliente, pero mi servidor (Django/Apache) se lee como una petición GET, sin parámetros GET - request.method produce ' GET ', request.GET.items() produce un diccionario vacío.

¿Qué estoy haciendo mal? En realidad, no sé cómo configurar correctamente los parámetros multiparte, estoy usando conjeturas, por lo que es posible que ese sea el problema.

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(); 
    } 
} 
+0

favor, eche un vistazo a esta pregunta respondida anteriormente http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk – Omie

Respuesta

0

que tenía el mismo problema con solicitud de MultipartEntity. Necesitaba subir la imagen al servidor. Así que hice la solicitud MultipartEntity por la clase HttpURLConnection. Puse aquí mi código, creo que puede ser útil para usted. Necesita establecer la ruta de la URL y la ruta del archivo. Para este método de uso puesto.

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; 
}} 
Cuestiones relacionadas