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

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

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

5条回答
  •  Happy的楠姐
    2020-11-22 12:48

    the most effective method is to use android-async-http

    You can use this code to upload a file:

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

    Note that you can put this code directly into your main Activity, no need to create a background Task explicitly. AsyncHttp will take care of that for you!

提交回复
热议问题