HttpEntity在Android上已经被弃用了,有什么select?

随着Android 5.1的发布,它看起来像所有的Apache HTTP的东西已被弃用。 看文档是没用的; 他们都说

This class was deprecated in API level 22. Please use openConnection() instead. Please visit this webpage for further details.

当你第一次阅读它时是好的,但是当每个被弃用的类都这样说的时候,这并没有什么帮助。

无论如何,像HttpEntity类,特别是StringEntityMultipartEntity类的替代品是什么? 我用BasicNameValuePair替代了Android的Pair<T, S>类,它看起来像URLEncoder.encodeURLEncoder.encode的一个很好的替代品,但我不确定如何处理HttpEntity

编辑

我决定只是重新写networking的东西。 要尝试使用Retrofit和OkHttp

编辑

认真看看切换你的电话和东西改造。 相当漂亮。 我很高兴我做到了。 有几个障碍,但很酷。

你总是可以导入最后一个Apache Http客户端并使用它。 另外,你可能想看看像Volley或Retrofit这样的networking库,以防万一你可以使用它。 如果开始一个新项目,build议使用联网库,因为不需要重新发明轮子。 但是,如果你坚持使用HttpClient ,然后阅读。

编辑:最新的新闻在Apache HttpClient(截至11/07/2015)

Google Android 1.0发布了Apache HttpClient的beta版快照。 为了配合第一个Android版本,Apache HttpClient 4.0 API必须被过早地冻结,而许多接口和内部结构还没有完全解决。 随着Apache HttpClient 4.0的成熟,项目希望Google能够将最新的代码改进融入代码树中。 不幸的是,这并没有发生。 Android附带的Apache HttpClient版本已经成为一个分支。 最终谷歌决定停止进一步开发他们的分支,同时拒绝升级到Apache HttpClient的股票版本引用兼容性担忧作为这样的决定的一个原因。 因此,想要在Android上继续使用Apache HttpClient API的Android开发人员不能利用更新的function,性能改进和错误修复。 Android的Apache HttpClient 4.3端口旨在通过提供与Google Android兼容的正式版本来弥补这一状况。 鉴于从Android API 23谷歌的HttpClient叉已被删除,该项目已经停产。

不过,Apache HttpClient v4.3有一个官方的Android端口

Android API 22及更早版本应使用Apache HttpClient v4.3

 dependencies { compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1' } 

Android API 23和更高版本应该使用由Marek Sebera维护的 Android的Apache HttpClient包

 dependencies { compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1' } 

信息来自Apache.org

HttpClient文档指出你在正确的方向:

org.apache.http.client.HttpClient

此接口在API级别22中已弃用。请改为使用openConnection()。 请访问此网页了解更多详情。

意味着你应该切换到java.net.URL.openConnection()

以下是你如何做到这一点:

 java.net.URL url = new java.net.URL("http://some-server"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); // read the response System.out.println("Response Code: " + conn.getResponseCode()); InputStream in = new BufferedInputStream(conn.getInputStream()); String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8"); System.out.println(response); 

通过httpurlconnection调用webservice httpclientreplace

我的代码在这里

 public static String getDataFromUrl(String url) { String result = null; // System.out.println("URL comes in jsonparser class is: " + url); try { URL myurl=new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) myurl .openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); urlConnection.connect(); InputStream is=urlConnection.getInputStream(); if (is != null) { StringBuilder sb = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader( new InputStreamReader(is)); while ((line = reader.readLine()) != null) { sb.append(line); } reader.close(); } finally { is.close(); } result = sb.toString(); } }catch (Exception e){ result=null; } return result; }