HttpPost de Android con parámetros y archivo


Necesito subir algunos datos al servidor PHP. Puedo hacer post con parámetros:

String url = "http://yourserver";

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("user", "username"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    httpClient.execute(httpPost);
}

También puedo subir un archivo:

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...
}

Pero, ¿cómo puedo armarlo? Necesito subir una imagen y parámetros en un post. Gracias

Author: Kelib, 2012-10-22

4 answers

Debe usar un post http multiparte, como en los formularios HTML. Esto se puede hacer con una biblioteca adicional. Vea el post Enviando imágenes usando Http Post para un ejemplo completo.

 10
Author: rgrocha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:09:01

Tienes que usar MultipartEntity. Busque en línea y descargue esas dos bibliotecas: httpmime-4.0.jar y apache-mime4j-0.4.jar y luego puede adjuntar tantas cosas como desee. Aquí hay un ejemplo de cómo usarlo:

HttpPost httpost = new HttpPost("URL_WHERE_TO_UPLOAD");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myString", new StringBody("STRING_VALUE"));
entity.addPart("myImageFile", new FileBody(imageFile));
entity.addPart("myAudioFile", new FileBody(audioFile));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);

Y para el lado del servidor puede usar estos nombres de identificador de entidadmyImageFile, myString y myAudioFile.

 12
Author: Marcin S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-27 22:41:27

Esto funciona como un encanto para mí:

public int uploadFile(String sourceFileUri) {  

    String fileName=sourceFileUri;
    HttpURLConnection conn = null;
    DataOutputStream dos = null;  
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "------hellojosh";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024; 
    File sourceFile = new File(fileName); 
    Log.e("joshtag", "Uploading: sourcefileURI, "+fileName);

    if (!sourceFile.isFile()) {                                
         Log.e("uploadFile", "Source File not exist :"+appSingleton.getInstance().photouri);//FullPath);                
         runOnUiThread(new Runnable() {
            public void run() {             
                //messageText.setText("Source File not exist :"
                }
            });          
         return 0;  //RETURN #1
         }
    else{
        try{                

             FileInputStream fileInputStream = new FileInputStream(sourceFile);           
             URL url = new URL(upLoadServerUri);
             Log.v("joshtag",url.toString());

             // Open a HTTP  connection to  the URL
             conn = (HttpURLConnection) url.openConnection(); 
             conn.setDoInput(true); // Allow Inputs
             conn.setDoOutput(true); // Allow Outputs
             conn.setUseCaches(false); // Don't use a Cached Copy            s       
             conn.setRequestMethod("POST");                     
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);     
             conn.setRequestProperty("file", fileName);                     
             conn.setRequestProperty("user", user_id));

             dos = new DataOutputStream(conn.getOutputStream());  
             //ADD Some -F Form parameters, helping method
             //... is declared down below
             addFormField(dos, "someParameter", "someValue");

             dos.writeBytes(twoHyphens + boundary + lineEnd); 
             dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd);                    
             dos.writeBytes(lineEnd);      

             // create a buffer of  maximum size
             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);
                    Log.i("joshtag","->");
                    }

             // send multipart form data necesssary after file data...
             dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

             // Responses from the server (code and message)
             serverResponseCode = conn.getResponseCode();
             String serverResponseMessage = conn.getResponseMessage().toString();              
             Log.i("joshtag", "HTTP Response is : "  + serverResponseMessage + ": " + serverResponseCode);  

             // ------------------ read the SERVER RESPONSE
             DataInputStream inStream;
             try {
                 inStream = new DataInputStream(conn.getInputStream());
                 String str;
                 while ((str = inStream.readLine()) != null) {
                     Log.e("joshtag", "SOF Server Response" + str);
                    }
                 inStream.close();
                }
             catch (IOException ioex) {
                Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);
                }

             //close the streams //
             fileInputStream.close();
             dos.flush();
             dos.close();    

             if(serverResponseCode == 200){ 
                //Do something                       
                }//END IF Response code 200  

            dialog.dismiss();
            }//END TRY - FILE READ      
        catch (MalformedURLException ex) {
            ex.printStackTrace();     
            Log.e("joshtag", "UL error: " + ex.getMessage(), ex);  
            } //CATCH - URL Exception

         catch (Exception e) {           
            e.printStackTrace();             
            Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
            } //

        return serverResponseCode; //after try       
        }//END ELSE, if file exists.
    }


public static String lineEnd = "\r\n";
public static String twoHyphens = "--";
public static String boundary = "------------------------afb19f4aeefb356c";
public static void addFormField(DataOutputStream dos, String parameter, String value){
    try {
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\""+parameter+"\"" + lineEnd);
        dos.writeBytes(lineEnd);
        dos.writeBytes(value);
        dos.writeBytes(lineEnd);
    }
    catch(Exception e){

    }
}

ACTUALIZACIÓN: Si necesita enviar parámetros junto con el archivo, uso:

conn.setRequestProperty("someParameter","someValue")
//or
addFormField(DataOutputStream dos, String parameter, String value)

As como se muestra en el código anterior. Uno u otro debería funcionar, si el servidor al que está intentando conectarse no es completamente conocido por usted.

 4
Author: Josh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-20 08:40:40

Ten cuidado

MultiPartEntity y BasicNameValuePairson obsoletos.

Así que aquí está la nueva manera de hacerlo! Y solo necesitas httpcore.jar(latest) y httpmime.jar(latest) descargarlos desde el sitio Apache .

try
{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(URL);

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    entityBuilder.addTextBody(USER_ID, userId);
    entityBuilder.addTextBody(NAME, name);
    entityBuilder.addTextBody(TYPE, type);
    entityBuilder.addTextBody(COMMENT, comment);
    entityBuilder.addTextBody(LATITUDE, String.valueOf(User.Latitude));
    entityBuilder.addTextBody(LONGITUDE, String.valueOf(User.Longitude));

    if(file != null)
    {
        entityBuilder.addBinaryBody(IMAGE, file);
    }

    HttpEntity entity = entityBuilder.build();
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    HttpEntity httpEntity = response.getEntity();
    result = EntityUtils.toString(httpEntity);
    Log.v("result", result);
}
catch(Exception e)
{
    e.printStackTrace();
}
 1
Author: Adnan Abdollah Zaki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-27 21:44:51