Search code examples
javaandroidapihttp-postapache-commons-httpclient

I need an alternative option to HttpClient in Android to send data to PHP as it is no longer supported


Currently I'm using HttpClient, HttpPost to send data to my PHP server from an Android app but all those methods were deprecated in API 22 and removed in API 23, so what are the alternative options to it?

I searched everywhere but I didn't find anything.


Solution

  • The HttpClient was deprecated and now removed:

    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().

    See also the new HttpURLConnection documentation.

    Here's how you could do it:

    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 documentation: Apache Commons IO
    IOUtils Maven dependency: http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar