【问题标题】:httpclient.Execute very slow on Androidhttpclient.Execute 在 Android 上很慢
【发布时间】:2012-09-27 11:50:39
【问题描述】:

我正在使用 httpclient.execute(httppost) 大约需要 10 秒才能将一个小文件发送到我的网络服务器。当我使用手机上的网络浏览器上传相同的文件时,只需不到 1 秒。这是我的代码

   String urlString = "http://xxxxx/upload.php";

        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        DefaultHttpClient httpclient = new DefaultHttpClient(params);
        HttpPost httppost = new HttpPost(urlString);

        File file = new File(pic);

        Log.d(TAG, "UPLOAD: setting up multipart entity");

        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        Log.d(TAG, "UPLOAD: file length = " + file.length());
        Log.d(TAG, "UPLOAD: file exist = " + file.exists());

        mpEntity.addPart("uploadedfile", new FileBody(file, "application/octet"));
     // mpEntity.addPart("id", new StringBody("1"));

        httppost.setEntity(mpEntity);
        Log.d(TAG, "UPLOAD: executing request: " + httppost.getRequestLine());
        Log.d(TAG, "UPLOAD: request: " + httppost.getEntity().getContentType().toString());


        HttpResponse response;
        try {
            Log.d(TAG, "UPLOAD: about to execute");
            response = httpclient.execute(httppost);
            Log.d(TAG, "UPLOAD: executed");
            HttpEntity resEntity = response.getEntity();
            Log.d(TAG, "UPLOAD: respose code: " + response.getStatusLine().toString());
            if (resEntity != null) {
                Log.d(TAG, "UPLOAD: " + EntityUtils.toString(resEntity));
            }
            if (resEntity != null) {
                resEntity.consumeContent();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Android 上是否存在阻止从应用内快速上传文件的错误?

【问题讨论】:

    标签: android


    【解决方案1】:

    Android 团队建议使用HttpUrlConnection 而不是HttpClient http://android-developers.blogspot.com/2011/09/androids-http-clients.html

    【讨论】:

    • 谢谢你,我也厌倦了 HttpUrlConnection 并且它非常慢。我在这里问了一个问题stackoverflow.com/questions/12581289/…。我决定尝试使用另一种方法,因为似乎没有解决方案?
    • 谢谢,还是一样。上传似乎很快,但读取响应需要很长时间。
    • 您需要回复文本吗?也许只需检查HttpUrlConnections.getResponseCode 就可以在不打开输入流的情况下完成工作?
    • 我需要从服务器获取 html 回复。很奇怪,当我调用 inStream = new DataInputStream(connection.getInputStream()); 时,文件没有复制到服务器。命令。确实应该在调用它之前复制文件吗?
    猜你喜欢
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 2012-08-19
    相关资源
    最近更新 更多