Подтвердить что ты не робот

Android httpPost с параметрами и файлом

Мне нужно загрузить некоторые данные на сервер PHP. Я могу делать сообщения с параметрами:

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);
}

Я также могу загрузить файл:

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...
}

Но как я могу собрать это вместе? Мне нужно загрузить изображение и параметры в одном сообщении. Благодаря

4b9b3361

Ответ 2

Вам нужно использовать MultipartEntity. Найдите в Интернете и загрузите эти две библиотеки: httpmime-4.0.jar и apache-mime4j-0.4.jar, а затем вы можете прикрепить столько, сколько хотите. Вот пример того, как его использовать:

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);

а для серверной стороны вы можете использовать имена этих идентификаторов объектов myImageFile, myString и myAudioFile.

Ответ 3

Это работает как прелесть для меня:

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){

    }
}

UPDATE: если вам нужно отправить параметры вместе с файлом, используйте:

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

... как показано в приведенном выше коде. Один или другой должен работать, если сервер, к которому вы пытаетесь подключиться, не полностью вам известен.

Ответ 4

будьте осторожны

MultiPartEntity и BasicNameValuePair исправлены.

Итак, вот новый способ сделать это! И вам нужно только httpcore.jar(latest) и httpmime.jar(latest) загрузить их с 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();
}