Post multipart request with Android SDK

前端 未结 12 1832
余生分开走
余生分开走 2020-11-22 04:38

I\'m trying to do something I thought would be relatively simple: Upload an image to a server with the Android SDK. I\'m found a lot of example code:

http://groups.g

12条回答
  •  攒了一身酷
    2020-11-22 05:25

    Remove all your httpclient, httpmime dependency and add this dependency compile 'commons-httpclient:commons-httpclient:3.1'. This dependency has built in MultipartRequestEntity so that you can easily upload one or more files to the server

    public class FileUploadUrlConnection extends AsyncTask {
    private Context context;
    private String url;
    private List files;
    
    public FileUploadUrlConnection(Context context, String url, List files) {
        this.context = context;
        this.url = url;
        this.files = files;
    }
    
    @Override
    protected String doInBackground(String... params) {
    
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(url);
        HttpClientParams connectionParams = new HttpClientParams();
    
        post.setRequestHeader(// Your header goes here );
    
        try {
            Part[] parts = new Part[files.size()];
            for (int i=0; i

    You can also add the request and response timeout

    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
    

提交回复
热议问题