【问题标题】:Alternate for HttpClient in android?在android中替代HttpClient?
【发布时间】:2015-05-05 09:53:39
【问题描述】:

我的要求是使用 Multipart 请求将图像上传到服务器。我能够使用已弃用的HttpClient 创建Multipart Http Request。是否可以使用HttpUrlConnection 实现相同的目标?如果是,怎么做?

更新:

当前代码

{
    ProgressDialog progress_dialog;

    @Override
        protected void onPreExecute() {
        // setting progress bar to zero
        progress_dialog=new ProgressDialog(CreateAlbum.this);
        progress_dialog.setTitle("Loading..");
        progress_dialog.show();

        super.onPreExecute();
    }

    @Override
        protected String doInBackground(Void... params) {
            return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.42:8080/test/fileUpload.php");

        try
        {
            MultipartEntityBuilder entity = MultipartEntityBuilder.create();        
            entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            File sourceFile = new File(fileUri);

            // Adding file data to http body
            entity.addPart("image", new FileBody(sourceFile));

            // Extra parameters if you want to pass to server
            entity.addPart("website",
                            new StringBody("www.androidhive.info"));
            entity.addPart("email", new StringBody("abc@gmail.com"));

            httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            Log.i("RAE", "STATUS CODE IS"+statusCode);
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
            } else {
                responseString = "Error occurred! Http Status Code: "
                                + statusCode;
            }

        } catch (ClientProtocolException e) {
                responseString = e.toString();
        } catch (IOException e) {
                responseString = e.toString();
        }
        return responseString;

    }

    @Override
    protected void onPostExecute(String result) {
        Log.e("RAE", "Response from server: " + result);
        progress_dialog.dismiss();
        // showing the server response in an alert dialog
        Toast.makeText(getApplicationContext(), "File Uploaded", Toast.LENGTH_SHORT).show();

        super.onPostExecute(result);
    }

}

【问题讨论】:

标签: java android httpurlconnection android-networking


【解决方案1】:

AndroidHttpClient 已贬值,不再得到开发人员的支持。所以必须在java.net 包下使用java 自己的HttpURLConnection。这是一个实现HttpURLConnection 的演示android 应用程序。只需使用以下git 命令并在android studio 中运行应用程序

克隆 git 项目:-

git clone https://github.com/viper-pranish/android-tutorial.git

下载实现HttpURLConnection的正确版本的项目

git checkout 399e3d1f9624353e522faf350f38a12db635c09a

【讨论】:

    【解决方案2】:

    编辑

    在您从我的代码中了解如何使用HttpUrlConnection 进行 POST 后,您可以对其进行编辑并整合以下答案:Sending files using POST with HttpURLConnection


    这就是我制作表单编码 POST 的方式:

    // Connection
    URL url = new URL("http://www.example.com");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    
    // Data to be sent
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeBytes(printParams(params));
    out.flush();
    out.close();
    
    // Print received response
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }
    in.close();
    

    其中printParams 是一个将Map 转换为a=b&c=d 之类的字符串的简单函数:

    public static String printParams(Map<String, String> params) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> e: params.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(e.getKey()).append('=').append(e.getValue());
        }
        return sb.toString();
    }
    

    【讨论】:

    • 是多部分请求吗?? @保险库
    • @vault,OP 无法投票,没有足够的声誉。如果您阅读了帮助部分,您就会知道...
    • 我知道伙计们,我也应该在某个地方拥有那个徽章:P
    • 你应该拥有哪个徽章?
    • Tour 徽章。回到主题,您还需要什么来解决您的问题?
    【解决方案3】:

    此链接包含使用 multipart 将文件发送到服务器所需的一切。它已更新为使用 android 中最新的 http 类。我已经对其进行了测试并今天自己使用它。干杯!

    http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/

    【讨论】:

    • 我认为您没有阅读问题详细信息。这个例子有弃用的类。我想避免弃用代码。 @史蒂夫
    【解决方案4】:

    对于接下来的帖子显示您的代码,程序员需要看到以提供更多帮助,谢谢。一方面,我总是在我的应用程序中使用 httpClient,这对我来说是最好的方式,因为你可以配置一个特定的客户端来处理 cookie、身份验证、连接管理和其他功能,如果你有代码就很简单。如果您想查看此主题的更多信息,您可以访问此链接,在 Class Overview 部分:

    http://developer.android.com/reference/org/apache/http/client/HttpClient.html http://developer.android.com/reference/java/net/HttpURLConnection.html

    另一方面,如果您想与您的服务器建立多个连接,我建议使用带有进程和线程的 httpClient 进行并行编程,可以在此处阅读更多信息:http://developer.android.com/guide/components/processes-and-threads.html


    // 最后更新 //

    抱歉,Rahul Batra 我使用 API 21...我在下一个版本的应用程序中注意到了这一点。但作为第一步,我将尝试使用带有 httpURLConnection 的背景任务。 这篇文章有一个非常好的信息:

    http://android-developers.blogspot.com.es/2011/09/androids-http-clients.html


    我希望它可以帮助你这个答案!如果您需要更多信息或任何事情,请告诉我,祝 Rahul Batra 好运。

    【讨论】:

    • 但是我现在不推荐使用 httpclient @Merli Perez Escarpentar
    • 哇,我有来自 android studio 的最新版本,而且我的课程没有被弃用 @RahulBatra :O
    • Perez Escarpentar 你可能没有最新版本的 Android sdk 使用 5.1
    • 感谢您提供此信息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 2019-09-11
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多