我需要Android中的HttpClient替代选项,以便将数据发送到PHP,因为它不再受支持

时间:2015-03-15 08:32:53

标签: java android api http-post httpclient

目前,我正在使用HttpClientHttpPostPHP server向我的Android app发送数据,但所有这些方法都在API 22中弃用,并在API 23,那么它有哪些备选方案呢?

我到处搜索,但我找不到任何东西。

9 个答案:

答案 0 :(得分:40)

我也遇到过这个问题要解决我自己上课的问题。 其中基于java.net,并支持Android的API 24 请检查一下: HttpRequest.java

您可以轻松地使用此课程:

  1. 发送Http GET请求
  2. 发送Http POST请求
  3. 发送Http PUT请求
  4. 发送Http DELETE
  5. 发送没有额外数据的请求参数&检查回复HTTP status code
  6. 添加自定义HTTP Headers以请求(使用varargs)
  7. 将数据参数添加为String查询以请求
  8. 将数据参数添加为HashMap {key = value}
  9. 接受回复为String
  10. 接受回复为JSONObject
  11. 接受响应为byte []字节数组(对文件有用)
  12. 以及它们的任意组合 - 只需一行代码)

    以下是一些例子:

    //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/b.c" in background  using AsyncTask
    new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                try {
                    response=new HttpRequest("http://url.com/b.c").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();
    

答案 1 :(得分:28)

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://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar

答案 2 :(得分:7)

以下代码位于AsyncTask中:

在我的后台流程中:

String POST_PARAMS = "param1=" + params[0] + "&param2=" + 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

答案 3 :(得分:3)

这是我已经应用于httpclient在此版本的android 22中弃用的问题的解决方案。

 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;
    }

}

答案 4 :(得分:2)

您可以继续使用HttpClient。谷歌仅弃用他们自己的Apache组件版本。你可以像我在这篇文章中描述的那样安装新的,功能强大且不被弃用的Apache HttpClient版本:https://stackoverflow.com/a/37623038/1727132

答案 5 :(得分:1)

  

哪个客户最好?

     

Apache HTTP客户端在Eclair和Froyo上的错误更少。这是最好的   这些版本的选择。

     

对于Gingerbread而言,更好的是,HttpURLConnection是最佳选择。它的   简单的API和小巧的尺寸使其非常适合Android ...

参考here了解更多信息(Android开发人员博客)

答案 6 :(得分:1)

如果针对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作为解决方法。这似乎是Google自己的一些gms库所必需的!

答案 7 :(得分:1)

您可以使用我易于使用的自定义类。 只需创建抽象类的对象(Anonymous)并定义onsuccess()和onfail()方法。 https://github.com/creativo123/POSTConnection

答案 8 :(得分:-1)

我在使用 HttpClent HttpPost 方法时遇到类似问题,因为我不想更改我的代码,所以我在build.gradle(模块)中找到了备用选项删除&#39; rc3&#39;来自buildToolsVersion&#34; 23.0.1 rc3&#34;它对我有用。希望有助于。