如何在android中上传进度到服务器?

时间:2016-08-02 09:26:54

标签: android http-post

我使用下面发布的代码将图像文件上传到服务器。现在我想获取上传的文件大小,以显示上传文件百分比的进度。因此,我需要在executeInternal()方法中上传文件大小,即bytesWritten大小。这是代码:

 public Response createTooteet(int type, String id, HttpEntity entity, String filePath) {
        HttpPost httpPost = new HttpPost(getUrlByType(type));
        addHeader(httpPost, id);
        httpPost.addHeader(entity.getContentType());
        httpPost.setEntity(entity);
        return execute(httpPost, entity, filePath);
    }

     private Response execute(HttpPost httpPost, HttpEntity entity, String filePath) {
        return executeInternal(0, httpPost, entity, filePath);
    }

      private Response executeInternal(int retry, HttpPost httpPost, HttpEntity entity, String filePath) {

        String content = null;
        int responseCode = -1;

        try {
            if (Constants.DEBUG) {
                try{
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    entity.writeTo(bout);
//                    Log.e(TAG, "url:" + httpPost.getRequestLine().toString());
                }catch (Exception e){
//                    Log.d(TAG,"out of memory exception________________"+e.getMessage());
                    e.printStackTrace();
                }

            }

            HttpResponse response = mHttpClient.execute(httpPost);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent(), "UTF-8"));
            responseCode = response.getStatusLine().getStatusCode();
            StringBuilder s = new StringBuilder();
            String sResponse;
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            content = s.toString();

            if (Constants.DEBUG) {
                //Log.e(TAG, "response:" + responseCode + "-" + content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Response response = new Response(responseCode, content);
        if (!response.isSuccess() && response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED && retry == 0) {
            if (login()) {
                httpPost.setHeader(ParamNames.USER_TOKEN, mUserPreference.getUserToken());
                return executeInternal(retry + 1, httpPost, entity, filePath);
            } else {
                return new Response(0, StatusCodes.LoginHandler.getErrorMessage(mContext, 0));
            }
        }

//        Log.d("Server request-----","response" + response.getContent() + " suc" + response.isSuccess());

        return response;
    } 

我如何获取已经上传的当前文件的数量值?

0 个答案:

没有答案