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

9

30

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.

Apartment answered 15/3, 2015 at 8:32 Comment(2)
You should clarify what platform you are on (java, php, ruby?) and what library+version you are using now, and to what library+version you are trying to update to (include the exact versions and library names).Belvia
I am sending data from Android app to PHP using HttpPost and HttpClient but these methods are deprecated in the new update of API 22 so i need some option to thatApartment
B
31

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

Belvia answered 15/3, 2015 at 11:18 Comment(2)
What is IOUtils in your answer?Balance
Improved the answer by adding links to the Commons IO (IOUtils) documentation and the maven search site.Belvia
R
43

I've also encountered with this problem to solve that I've made my own class. Which based on java.net, and supports up to android's API 24 please check it out: HttpRequest.java

Using this class you can easily:

  1. Send Http GET request
  2. Send Http POST request
  3. Send Http PUT request
  4. Send Http DELETE
  5. Send request without extra data params & check response HTTP status code
  6. Add custom HTTP Headers to request (using varargs)
  7. Add data params as String query to request
  8. Add data params as HashMap {key=value}
  9. Accept Response as String
  10. Accept Response as JSONObject
  11. Accept response as byte [] Array of bytes (useful for files)

and any combination of those - just with one single line of code)

Here are a few examples:

//Consider next request: 
HttpRequest req=new HttpRequest("http://host:port/path");

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

Example 2:

// prepare http get request,  send to "http://host:port/path" and read server's response as String 
req.prepare().sendAndReadString();

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

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

Example 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

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

Example 7:

//Downloading file
byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes();
FileOutputStream fos = new FileOutputStream("smile.png");
fos.write(file);
fos.close();
Radically answered 30/7, 2015 at 21:36 Comment(4)
Looks like the proper answer to this questionSaiff
Best Example for deprecated httpClient, NameValuePair. Recommence to other.Knox
how about upload file to server?Nosebleed
@DavidUntama Just send it as JSON and then use GSON.fromJson on your server to parse it.Radically
B
31

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

Belvia answered 15/3, 2015 at 11:18 Comment(2)
What is IOUtils in your answer?Balance
Improved the answer by adding links to the Commons IO (IOUtils) documentation and the maven search site.Belvia
H
7

The following code is in an AsyncTask:

In my background process:

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

Reference: http://www.journaldev.com/7148/java-httpurlconnection-example-to-send-http-getpost-requests

Healion answered 26/6, 2015 at 6:0 Comment(0)
D
3

This is the solution that I have applied to the problem that httpclient deprecated in this version of 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;
    }

}
Dropline answered 1/9, 2015 at 7:13 Comment(0)
A
2

You are free to continue using HttpClient. Google deprecated only their own version of Apache's components. You can install fresh, powerful and non deprecated version of Apache's HttpClient like I described in this post: https://mcmap.net/q/57243/-android-deprecated-apache-module-httpclient-httpresponse-etc

Auspicious answered 5/6, 2016 at 20:51 Comment(0)
C
2

if targeted for API 22 and older, then should add the following line into build.gradle

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

if targeted for API 23 and later, then should add the following line into build.gradle

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

If still want to use httpclient library, in Android Marshmallow (sdk 23), you can add:

useLibrary 'org.apache.http.legacy'

to build.gradle in the android {} section as a workaround. This seems to be necessary for some of Google's own gms libraries!

Controvert answered 5/7, 2017 at 19:3 Comment(0)
T
1

Which client is best?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android...

Reference here for more info (Android developers blog)

Titania answered 24/5, 2016 at 14:29 Comment(0)
C
1

You can use my easy to use custom class. Just create an object of the abstract class(Anonymous) and define onsuccess() and onfail() method. https://github.com/creativo123/POSTConnection

Catty answered 20/8, 2017 at 16:39 Comment(1)
I believe it's better to use HttpURLConnection, as described in https://mcmap.net/q/57678/-sending-post-data-in-android.Jaw
T
-1

i had similar issues in using HttpClent and HttpPost method since i didn't wanted change my code so i found alternate option in build.gradle(module) file by removing 'rc3' from buildToolsVersion "23.0.1 rc3" and it worked for me. Hope that Helps.

Tod answered 20/10, 2015 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.