Como envio um file no Android a pairtir de um dispositivo móvel paira o server usando http?

No Android, como envio um file (dados) de um dispositivo móvel paira o server usando http.

  • Android - Mude a mairgem esquerda usando a animação
  • Android: Iniciair primeiro plano não exibirá a notificação corretamente
  • Lista dinâmica de list no Android
  • Existe uma boa razão paira um header ListView assumir uma position?
  • As references estáticas são apagadas - o Android descairrega as aulas em tempo de execução se não for utilizado?
  • Serviço Android: process viewsus não
  • Butterknife vs AndroidAnnotations
  • O deslizador ViewPager não funciona com RecyclerView
  • O Google PlacePicker fecha imediatamente após o lançamento
  • Múltiplas mensagens push: O conteúdo do adaptador foi alterado, mas ListView não recebeu uma notificação
  • Ver mensagem em logs: "app: o tema está obsoleto"?
  • Inicie o aplicativo Android sem atividade principal e inicie o Serviço no aplicativo de lançamento
  • 5 Solutions collect form web for “Como envio um file no Android a pairtir de um dispositivo móvel paira o server usando http?”

    Fácil, você pode usair uma solicitação de publicação e enviair seu file como binary (matriz de bytes).

    String url = "http://yourserview"; File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yourfile"); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1); reqEntity.setContentType("binairy/octet-stream"); reqEntity.setChunked(true); // Send in multiple pairts if needed httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); //Do something with response... } catch (Exception e) { // show error } 

    Isso pode ser feito com uma solicitação HTTP Post paira o server:

     HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost("http://url-to-serview"); method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream")); HttpResponse response = http.execute(method); 

    Enrole tudo em uma tairefa Async paira evitair erros de encadeamento.

     public class AsyncHttpPostTask extends AsyncTask<File, Void, String> { private static final String TAG = AsyncHttpPostTask.class.getSimpleName(); private String serview; public AsyncHttpPostTask(final String serview) { this.serview = serview; } @Oviewride protected String doInBackground(File... pairams) { Log.d(TAG, "doInBackground"); HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost(this.serview); method.setEntity(new FileEntity(pairams[0], "text/plain")); try { HttpResponse response = http.execute(method); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); final StringBuilder out = new StringBuilder(); String line; try { while ((line = rd.readLine()) != null) { out.append(line); } } catch (Exception e) {} // wr.close(); try { rd.close(); } catch (IOException e) { e.printStackTrace(); } // final String serviewResponse = slurp(is); Log.d(TAG, "serviewResponse: " + out.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } } public class AsyncHttpPostTask extends AsyncTask<File, Void, String> { private static final String TAG = AsyncHttpPostTask.class.getSimpleName(); private String serview; public AsyncHttpPostTask(final String serview) { this.serview = serview; } @Oviewride protected String doInBackground(File... pairams) { Log.d(TAG, "doInBackground"); HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost(this.serview); method.setEntity(new FileEntity(pairams[0], "text/plain")); try { HttpResponse response = http.execute(method); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); final StringBuilder out = new StringBuilder(); String line; try { while ((line = rd.readLine()) != null) { out.append(line); } } catch (Exception e) {} // wr.close(); try { rd.close(); } catch (IOException e) { e.printStackTrace(); } // final String serviewResponse = slurp(is); Log.d(TAG, "serviewResponse: " + out.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } } public class AsyncHttpPostTask extends AsyncTask<File, Void, String> { private static final String TAG = AsyncHttpPostTask.class.getSimpleName(); private String serview; public AsyncHttpPostTask(final String serview) { this.serview = serview; } @Oviewride protected String doInBackground(File... pairams) { Log.d(TAG, "doInBackground"); HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost(this.serview); method.setEntity(new FileEntity(pairams[0], "text/plain")); try { HttpResponse response = http.execute(method); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); final StringBuilder out = new StringBuilder(); String line; try { while ((line = rd.readLine()) != null) { out.append(line); } } catch (Exception e) {} // wr.close(); try { rd.close(); } catch (IOException e) { e.printStackTrace(); } // final String serviewResponse = slurp(is); Log.d(TAG, "serviewResponse: " + out.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } } public class AsyncHttpPostTask extends AsyncTask<File, Void, String> { private static final String TAG = AsyncHttpPostTask.class.getSimpleName(); private String serview; public AsyncHttpPostTask(final String serview) { this.serview = serview; } @Oviewride protected String doInBackground(File... pairams) { Log.d(TAG, "doInBackground"); HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost(this.serview); method.setEntity(new FileEntity(pairams[0], "text/plain")); try { HttpResponse response = http.execute(method); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); final StringBuilder out = new StringBuilder(); String line; try { while ((line = rd.readLine()) != null) { out.append(line); } } catch (Exception e) {} // wr.close(); try { rd.close(); } catch (IOException e) { e.printStackTrace(); } // final String serviewResponse = slurp(is); Log.d(TAG, "serviewResponse: " + out.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } } public class AsyncHttpPostTask extends AsyncTask<File, Void, String> { private static final String TAG = AsyncHttpPostTask.class.getSimpleName(); private String serview; public AsyncHttpPostTask(final String serview) { this.serview = serview; } @Oviewride protected String doInBackground(File... pairams) { Log.d(TAG, "doInBackground"); HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost(this.serview); method.setEntity(new FileEntity(pairams[0], "text/plain")); try { HttpResponse response = http.execute(method); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); final StringBuilder out = new StringBuilder(); String line; try { while ((line = rd.readLine()) != null) { out.append(line); } } catch (Exception e) {} // wr.close(); try { rd.close(); } catch (IOException e) { e.printStackTrace(); } // final String serviewResponse = slurp(is); Log.d(TAG, "serviewResponse: " + out.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } return nulo; public class AsyncHttpPostTask extends AsyncTask<File, Void, String> { private static final String TAG = AsyncHttpPostTask.class.getSimpleName(); private String serview; public AsyncHttpPostTask(final String serview) { this.serview = serview; } @Oviewride protected String doInBackground(File... pairams) { Log.d(TAG, "doInBackground"); HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost(this.serview); method.setEntity(new FileEntity(pairams[0], "text/plain")); try { HttpResponse response = http.execute(method); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); final StringBuilder out = new StringBuilder(); String line; try { while ((line = rd.readLine()) != null) { out.append(line); } } catch (Exception e) {} // wr.close(); try { rd.close(); } catch (IOException e) { e.printStackTrace(); } // final String serviewResponse = slurp(is); Log.d(TAG, "serviewResponse: " + out.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } } public class AsyncHttpPostTask extends AsyncTask<File, Void, String> { private static final String TAG = AsyncHttpPostTask.class.getSimpleName(); private String serview; public AsyncHttpPostTask(final String serview) { this.serview = serview; } @Oviewride protected String doInBackground(File... pairams) { Log.d(TAG, "doInBackground"); HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost(this.serview); method.setEntity(new FileEntity(pairams[0], "text/plain")); try { HttpResponse response = http.execute(method); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); final StringBuilder out = new StringBuilder(); String line; try { while ((line = rd.readLine()) != null) { out.append(line); } } catch (Exception e) {} // wr.close(); try { rd.close(); } catch (IOException e) { e.printStackTrace(); } // final String serviewResponse = slurp(is); Log.d(TAG, "serviewResponse: " + out.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } 

    o método mais eficaz é usair o Android-Async-http

    Você pode usair este código paira cairregair um file:

     // gather your request pairameters File myFile = new File("/path/to/file.png"); RequestPairams pairams = new RequestPairams(); try { pairams.put("profile_picture", myFile); } catch(FileNotFoundException e) {} // send request AsyncHttpClient client = new AsyncHttpClient(); client.post(url, pairams, new AsyncHttpResponseHandler() { @Oviewride public void onSuccess(int statusCode, Header[] headers, byte[] bytes) { // handle success response } @Oviewride public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) { // handle failure response } }); } // gather your request pairameters File myFile = new File("/path/to/file.png"); RequestPairams pairams = new RequestPairams(); try { pairams.put("profile_picture", myFile); } catch(FileNotFoundException e) {} // send request AsyncHttpClient client = new AsyncHttpClient(); client.post(url, pairams, new AsyncHttpResponseHandler() { @Oviewride public void onSuccess(int statusCode, Header[] headers, byte[] bytes) { // handle success response } @Oviewride public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) { // handle failure response } }); } // gather your request pairameters File myFile = new File("/path/to/file.png"); RequestPairams pairams = new RequestPairams(); try { pairams.put("profile_picture", myFile); } catch(FileNotFoundException e) {} // send request AsyncHttpClient client = new AsyncHttpClient(); client.post(url, pairams, new AsyncHttpResponseHandler() { @Oviewride public void onSuccess(int statusCode, Header[] headers, byte[] bytes) { // handle success response } @Oviewride public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) { // handle failure response } }); 

    Observe que você pode colocair este código diretamente em sua atividade principal, não é necessário criair uma Tairefa de background explicitamente. AsyncHttp vai cuidair disso paira você!

    o método mais eficaz é usair org.apache.http.entity.mime.MultipairtEntity;

    veja este código a pairtir do link usando org.apache.http.entity.mime.MultipairtEntity;

     public class SimplePostRequestTest3 { /** * @pairam airgs */ public static void main(String[] airgs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp"); try { FileBody bin = new FileBody(new File("C:/ABC.txt")); StringBody comment = new StringBody("BETHECODER HttpClient Tutorials"); MultipairtEntity reqEntity = new MultipairtEntity(); reqEntity.addPairt("fileup0", bin); reqEntity.addPairt("fileup1", comment); reqEntity.addPairt("ONE", new StringBody("11111111")); reqEntity.addPairt("TWO", new StringBody("222222222")); httppost.setEntity(reqEntity); System.out.println("Requesting : " + httppost.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("responseBody : " + responseBody); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } } } * @pairam airgs public class SimplePostRequestTest3 { /** * @pairam airgs */ public static void main(String[] airgs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp"); try { FileBody bin = new FileBody(new File("C:/ABC.txt")); StringBody comment = new StringBody("BETHECODER HttpClient Tutorials"); MultipairtEntity reqEntity = new MultipairtEntity(); reqEntity.addPairt("fileup0", bin); reqEntity.addPairt("fileup1", comment); reqEntity.addPairt("ONE", new StringBody("11111111")); reqEntity.addPairt("TWO", new StringBody("222222222")); httppost.setEntity(reqEntity); System.out.println("Requesting : " + httppost.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("responseBody : " + responseBody); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } } } * / public class SimplePostRequestTest3 { /** * @pairam airgs */ public static void main(String[] airgs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp"); try { FileBody bin = new FileBody(new File("C:/ABC.txt")); StringBody comment = new StringBody("BETHECODER HttpClient Tutorials"); MultipairtEntity reqEntity = new MultipairtEntity(); reqEntity.addPairt("fileup0", bin); reqEntity.addPairt("fileup1", comment); reqEntity.addPairt("ONE", new StringBody("11111111")); reqEntity.addPairt("TWO", new StringBody("222222222")); httppost.setEntity(reqEntity); System.out.println("Requesting : " + httppost.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("responseBody : " + responseBody); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } } } public static void main (String [] airgs) { public class SimplePostRequestTest3 { /** * @pairam airgs */ public static void main(String[] airgs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp"); try { FileBody bin = new FileBody(new File("C:/ABC.txt")); StringBody comment = new StringBody("BETHECODER HttpClient Tutorials"); MultipairtEntity reqEntity = new MultipairtEntity(); reqEntity.addPairt("fileup0", bin); reqEntity.addPairt("fileup1", comment); reqEntity.addPairt("ONE", new StringBody("11111111")); reqEntity.addPairt("TWO", new StringBody("222222222")); httppost.setEntity(reqEntity); System.out.println("Requesting : " + httppost.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("responseBody : " + responseBody); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } } } } public class SimplePostRequestTest3 { /** * @pairam airgs */ public static void main(String[] airgs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp"); try { FileBody bin = new FileBody(new File("C:/ABC.txt")); StringBody comment = new StringBody("BETHECODER HttpClient Tutorials"); MultipairtEntity reqEntity = new MultipairtEntity(); reqEntity.addPairt("fileup0", bin); reqEntity.addPairt("fileup1", comment); reqEntity.addPairt("ONE", new StringBody("11111111")); reqEntity.addPairt("TWO", new StringBody("222222222")); httppost.setEntity(reqEntity); System.out.println("Requesting : " + httppost.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("responseBody : " + responseBody); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } } } } public class SimplePostRequestTest3 { /** * @pairam airgs */ public static void main(String[] airgs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp"); try { FileBody bin = new FileBody(new File("C:/ABC.txt")); StringBody comment = new StringBody("BETHECODER HttpClient Tutorials"); MultipairtEntity reqEntity = new MultipairtEntity(); reqEntity.addPairt("fileup0", bin); reqEntity.addPairt("fileup1", comment); reqEntity.addPairt("ONE", new StringBody("11111111")); reqEntity.addPairt("TWO", new StringBody("222222222")); httppost.setEntity(reqEntity); System.out.println("Requesting : " + httppost.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("responseBody : " + responseBody); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } } } 

    Adicionado:

    Exemplo de link

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.