How do I send a file in Android from a mobile device to server using http?

后端 未结 5 1218
执笔经年
执笔经年 2020-11-22 12:04

In android, how do I send a file(data) from a mobile device to server using http.

5条回答
  •  攒了一身酷
    2020-11-22 12:30

    the most effective method is to use org.apache.http.entity.mime.MultipartEntity;

    see this code from the link using org.apache.http.entity.mime.MultipartEntity;

    public class SimplePostRequestTest3 {
    
      /**
       * @param args
       */
      public static void main(String[] args) {
        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");
    
          MultipartEntity reqEntity = new MultipartEntity();
          reqEntity.addPart("fileup0", bin);
          reqEntity.addPart("fileup1", comment);
    
          reqEntity.addPart("ONE", new StringBody("11111111"));
          reqEntity.addPart("TWO", new StringBody("222222222"));
          httppost.setEntity(reqEntity);
    
          System.out.println("Requesting : " + httppost.getRequestLine());
          ResponseHandler 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();
        }
      }
    
    }
    

    Added:

    Example Link

提交回复
热议问题