Misagh Emamverdi
Misagh Emamverdi

Reputation: 3674

Convert from AndroidHttpClient to HttpUrlConnection

I have written below code and it works fine:

private static final String URL = "http://test.net/api/mobile/logininfo";
private AndroidHttpClient client = AndroidHttpClient.newInstance("");

HttpPost request = new HttpPost(URL);
request.addHeader("Content-Type", "application/json; charset=utf-8");
request.addHeader("Cookie", sessionId);

String username = "test";
String osVersion = android.os.Build.VERSION.RELEASE;

String params = "{\"username\":\"" + username
                        + "\",\"osVersion\":\"" + osVersion
                        + "\"}";

request.setEntity(new StringEntity(params));
HttpResponse response = client.execute(request);

String res = new BasicResponseHandler()
                        .handleResponse(response);
                JSONObject obj = (JSONObject) new JSONTokener(res).nextValue();

//do something with JSONObject

However when I read developer best practices for network handling (http://android-developers.blogspot.com/2011/09/androids-http-clients.html) I found that HttpURLConnection is a better choice than AndroidHttpClient.

How can I convert my code to use HttpURLConnection instead of AndroidHttpClient?

Thanks

Upvotes: 1

Views: 501

Answers (1)

Misagh Emamverdi
Misagh Emamverdi

Reputation: 3674

I found the solution. Here is equivalent code for HttpURLConnection:

URL url = new URL("http://test.net/api/mobile/logininfo");
HttpURLConnection conn = (HttpURLConnection) url
        .openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Cookie", sessionId);
conn.setRequestProperty("Content-Type",
        "application/json; charset=utf-8");
conn.setRequestProperty("Expect", "100-continue");

String osVersion = android.os.Build.VERSION.RELEASE;

String params = "{\"username\":\"" + username
        + "\",\"osVersion\":\"" + osVersion
        + "\"}";

PrintWriter out = new PrintWriter(conn.getOutputStream());
out.println(params);
out.flush();

conn.connect();
int responseCode = conn.getResponseCode();

if (responseCode != 200)
        return null;

StringBuilder response = new StringBuilder();
        Scanner scanner = new Scanner(conn.getInputStream());
while (scanner.hasNext()) {
        response.append(scanner.nextLine());
}
scanner.close();

JSONObject obj = (JSONObject) new JSONTokener(
    response.toString()).nextValue();

//do something with JSONObject

Thanks

Upvotes: 1

Related Questions