使用MultipartEntity将图像加载到服务器时显示进度

时间:2012-03-15 15:46:35

标签: java android

我使用以下代码将图像发送到服务器:

public void loadImage(final File image) {
    new Thread(new Runnable() {
        public void run() {
            try{
                MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                entity.addPart("image", new FileBody(image));
                HttpResponse response=sendMultipart("http://myurl.net", entity);
            }catch(Exception e){
            }
        }
    }).start();
}

public HttpResponse sendMultipart(final String URL,MultipartEntity entity) throws IOException{
    HttpPost httpPost=new HttpPost(URL);
    httpPost.setEntity(entity);
    return sendRequest(httpPost);
}

public HttpResponse sendRequest(final HttpRequestBase mhttp) throws IOException{
    HttpParams params=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, REST.CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, REST.SERVER_TIMEOUT);
    HttpClient httpClient=new DefaultHttpClient(params);
    HttpResponse response=httpClient.execute(mhttp);

    //if we're been redirected then try to get relocated page
    if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
        Header [] headers=response.getHeaders("Location");
        if(headers!=null && headers.length!=0){
            String newUrl=headers[headers.length-1].getValue();
            HttpGet httpGet=new HttpGet(newUrl);
            response=httpClient.execute(httpGet);
        }
    }


    return response;
}

问题是:如何获得加载进度?

请注意,该问题不是“如何显示进度”,“如何加载图像”。我已经决定使用AsyncTask更好,但我仍然不知道如何取得进展。

0 个答案:

没有答案