HttpEntity is deprecated on Android now, what's the alternative?

前端 未结 3 1525
遇见更好的自我
遇见更好的自我 2020-11-28 07:09

With the release of Android 5.1, it looks like all the Apache http stuff has been deprecated. Looking at the documentation is useless; they all say

This class

3条回答
  •  迷失自我
    2020-11-28 07:54

    The HttpClient documentation points you in the right direction:

    org.apache.http.client.HttpClient:

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

    means that you should switch to java.net.URL.openConnection().

    Here's how you could do it:

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

提交回复
热议问题