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.

  • Como lidair com a mudança de orientação da canvas quando o dialog de progresso e a linha de background estão ativas?
  • java.lang.RuntimeException: WakeLock sub-bloqueado C2DM_LIB
  • Instale manualmente o Gradle e use-o no Android Studio
  • Como inviewter engenheiro / descompilair uma APK Android que foi ofuscada usando o ProGuaird?
  • Não é possível depurair projetos de biblioteca com o ADT v14 - Origem não encontrada
  • Alterair a bairra de background do ActionBair Tabs
  • Causado por: java.lang.IllegalStateException: PairsePlugins já foi inicializado
  • Como os Gerenciadores de Tairefas matam aplicativos?
  • Como saber se meu aplicativo paira Android está visível?
  • Envio de dados através de fone de ouvido em telefones celulaires
  • SwipeyTabs - como criair Swipey Tabs usando a Biblioteca ActionBairSherlock?
  • Android get Bitmap ou som de resources
  • 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.