我需要Android中的HttpClient的替代选项来将数据发送到PHP,因为它不再受支持
目前我正在使用HttpClient
, HttpPost
从Android app
发送数据到我的PHP server
,但所有这些方法在API 22中被弃用,并在API 23中删除,所以有什么替代select呢?
我到处search,但没有find任何东西。
HttpClient文档指出你在正确的方向:
org.apache.http.client.HttpClient
:
此接口在API级别22中已弃用。请改为使用openConnection()。 请访问此网页了解更多详情。
意味着你应该切换到java.net.URL.openConnection()
。
以下是你如何做到这一点:
URL url = new 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);
IOUtils
文档: Apache Commons IO
IOUtils
Maven依赖: http : IOUtils
我也遇到了这个问题,以解决我已经做了我自己的课程。 其中基于java.net,并支持达到android的API 24,请查看: HttpRequest.java
使用这个类,你可以很容易地:
- 发送Http
GET
请求 - 发送Http
POST
请求 - 发送Http
PUT
请求 - 发送Http
DELETE
- 发送无额外数据请求参数并检查响应
HTTP status code
- 添加自定义
HTTP Headers
请求(使用可变参数) - 添加数据参数作为
String
查询请求 - 将数据参数添加为
HashMap
{key = value} - 以
String
接受回应 - 接受Response作为
JSONObject
- 以
byte []
接受响应byte []
数组(对文件有用)
以及这些的任何组合 – 仅仅用一行代码)
这里有几个例子:
//Consider next request: HttpRequest req=new HttpRequest("http://host:port/path");
例1 :
//prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked req.prepare(HttpRequest.Method.POST).withData("name=Bubu&age=29").send();
例2 :
// prepare http get request, send to "http://host:port/path" and read server's response as String req.prepare().sendAndReadString();
例3 :
// prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29 and read server's response as JSONObject HashMap<String, String>params=new HashMap<>(); params.put("name", "Groot"); params.put("age", "29"); req.prepare(HttpRequest.Method.POST).withData(params).sendAndReadJSON();
例4 :
//send Http Post request to "http://url.com/bc" in background using AsyncTask new AsyncTask<Void, Void, String>(){ protected String doInBackground(Void[] params) { String response=""; try { response=new HttpRequest("http://url.com/bc").prepare(HttpRequest.Method.POST).sendAndReadString(); } catch (Exception e) { response=e.getMessage(); } return response; } protected void onPostExecute(String result) { //do something with response } }.execute();
例5 :
//Send Http PUT request to: "http://some.url" with request header: String json="{\"name\":\"Deadpool\",\"age\":40}";//JSON that we need to send String url="http://some.url";//URL address where we need to send it HttpRequest req=new HttpRequest(url);//HttpRequest to url: "http://some.url" req.withHeaders("Content-Type: application/json");//add request header: "Content-Type: application/json" req.prepare(HttpRequest.Method.PUT);//Set HttpRequest method as PUT req.withData(json);//Add json data to request body JSONObject res=req.sendAndReadJSON();//Accept response as JSONObject
例6 :
//Equivalent to previous example, but in a shorter way (using methods chaining): String json="{\"name\":\"Deadpool\",\"age\":40}";//JSON that we need to send String url="http://some.url";//URL address where we need to send it //Shortcut for example 5 complex request sending & reading response in one (chained) line JSONObject res=new HttpRequest(url).withHeaders("Content-Type: application/json").prepare(HttpRequest.Method.PUT).withData(json).sendAndReadJSON();
示例7 :
//Downloading file byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes(); FileOutputStream fos = new FileOutputStream("smile.png"); fos.write(file); fos.close();
以下代码在AsyncTask中:
在我的后台进程中:
String POST_PARAMS = "param1=" + params[0] + "¶m2=" + params[1]; URL obj = null; HttpURLConnection con = null; try { obj = new URL(Config.YOUR_SERVER_URL); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // For POST only - BEGIN con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(POST_PARAMS.getBytes()); os.flush(); os.close(); // For POST only - END int responseCode = con.getResponseCode(); Log.i(TAG, "POST Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { //success BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result Log.i(TAG, response.toString()); } else { Log.i(TAG, "POST request did not work."); } } catch (IOException e) { e.printStackTrace(); }
参考: http : //www.journaldev.com/7148/java-httpurlconnection-example-to-send-http-getpost-requests
这是我已经应用于这个版本的android 22`中的httpclient弃用的问题的解决scheme
public static final String USER_AGENT = "Mozilla/5.0"; public static String sendPost(String _url,Map<String,String> parameter) { StringBuilder params=new StringBuilder(""); String result=""; try { for(String s:parameter.keySet()){ params.append("&"+s+"="); params.append(URLEncoder.encode(parameter.get(s),"UTF-8")); } String url =_url; URL obj = new URL(_url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "UTF-8"); con.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream()); outputStreamWriter.write(params.toString()); outputStreamWriter.flush(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + params); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine + "\n"); } in.close(); result = response.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); }finally { return result; } }
哪个客户最好?
Apache HTTP客户端在Eclair和Froyo上有更less的错误。 这是这些版本的最佳select。
对于姜饼和更好,HttpURLConnection是最好的select。 它的简单API和小尺寸使其非常适合Android …
有关更多信息(Android开发人员博客)
你可以继续使用HttpClient。 Google仅弃用他们自己的Apache组件版本。 你可以像我这篇文章中描述的那样安装Apache的HttpClient的全新,强大和不被弃用的版本: https : //stackoverflow.com/a/37623038/1727132
如果针对API 22及更高版本,则应将以下行添加到build.gradle中
dependencies { compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1' }
如果针对API 23及更高版本,则应将以下行添加到build.gradle中
dependencies { compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1' }
如果还想使用httpclient库,在Android Marshmallow(sdk 23)中,可以添加:
useLibrary 'org.apache.http.legacy'
在android {}部分中构build.gradle作为解决方法。 这似乎是一些谷歌自己的gms库所必需的!
你可以使用我的易于使用的自定义类。 只需创build抽象类(匿名)的对象并定义onsuccess()和onfail()方法。 https://github.com/creativo123/POSTConnection
我在使用HttpClent和HttpPost方法有类似的问题,因为我不想更改我的代码,所以我通过从buildToolsVersion“23.0.1 rc3”中删除“rc3”在build.gradle(模块)文件中find备用选项,它为我工作。 希望有所帮助。