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

后端 未结 5 1183
执笔经年
执笔经年 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:46

    Easy, you can use a Post request and submit your file as binary (byte array).

    String url = "http://yourserver";
    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("binary/octet-stream");
        reqEntity.setChunked(true); // Send in multiple parts if needed
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        //Do something with response...
    
    } catch (Exception e) {
        // show error
    }
    

提交回复
热议问题