Java android中HttpClient的替代方案?

Java android中HttpClient的替代方案?,java,android,httpurlconnection,android-networking,Java,Android,Httpurlconnection,Android Networking,我的要求是使用多部分请求将图像上传到服务器。我能够使用HttpClient创建一个多部分Http请求,该请求已被弃用。是否可以使用HttpUrlConnection实现同样的功能?如果是,如何进行 更新: 现行代码 { ProgressDialog progress_dialog; @Override protected void onPreExecute() { // setting progress bar to zero p

我的要求是使用多部分请求将图像上传到服务器。我能够使用
HttpClient
创建一个
多部分Http请求
,该请求已被弃用。是否可以使用
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);
    }

}
编辑

从我的代码中了解如何使用
HttpUrlConnection
发表文章后,您可以对其进行编辑并整合以下答案:


这是我制作表单编码帖子的方式:

// 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();
}
公共静态字符串printparms(映射参数){
StringBuffer sb=新的StringBuffer();
对于(Map.Entry e:params.entrySet()){
如果(sb.length()>0){
某人附加(“&”);
}
sb.append(e.getKey()).append('=').append(e.getValue());
}
使某人返回字符串();
}

此链接包含使用multipart将文件发送到服务器所需的所有内容。它已经更新为使用android中最新的http类。我已经测试过了,今天我自己就用上了。干杯


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

另一方面,如果您想与服务器进行多重连接,我建议您使用带有进程和线程的httpClient并行编程,您可以在此处阅读更多信息:


//最后更新//

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



我希望它能帮助你回答这个问题!!如果您需要更多信息或其他任何信息,请告诉我,祝您好运Rahul Batra。

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

克隆git项目:-

git clone https://github.com/viper-pranish/android-tutorial.git
下载实现了
HttpURLConnection
的项目的正确版本

git checkout 399e3d1f9624353e522faf350f38a12db635c09a

您能显示您的实际HttpClient代码吗?@JordiCastilla查看我的更新问题WARE是多部分请求的可能副本@vault@vault,OP无法否决,声誉不够。如果你读了帮助部分,你就会知道…我知道伙计们,我也应该在某个地方有那个徽章:你应该有哪个徽章?徽章。回到话题上来,你还需要什么来解决你的问题?我想你没有阅读问题的细节。此示例包含已弃用的类。我希望避免使用depcrate代码@SteveBut httpclient我现在不推荐@Merli Perez Escarpentarw我有android studio的最新版本,我的类也没有不推荐@RahulBatra:OPerez Escarpentar你可能没有最新版本的android sdk使用5.1阅读此@MerliThanks了解这些信息!!