6

I am creating an Android application and I send data from Android application to servlet through HttpClient. I use HttpPost method.

I read in Android developer site that Apache HttpClient library has some bug in Android Froyo 2.2 and after all it's good practice to use HttpUrlConnection instead HttpPost. So I want to convert my HttpPost code to HttpUrlConnectio but don't know how.

I am posting my Android code as well as servlet code here

Android code

private String postData(String valueIWantToSend[]) 
    {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        try 
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("param1",valueIWantToSend[0]));
            nameValuePairs.add(new BasicNameValuePair("param2", valueIWantToSend[1]));
            nameValuePairs.add(new BasicNameValuePair("param3", valueIWantToSend[2]));
            nameValuePairs.add(new BasicNameValuePair("param4", valueIWantToSend[3]));
            nameValuePairs.add(new BasicNameValuePair("param5", valueIWantToSend[4]));
            nameValuePairs.add(new BasicNameValuePair("param6", valueIWantToSend[5]));
            nameValuePairs.add(new BasicNameValuePair("param7", valueIWantToSend[6]));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            /* execute */
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity rp = response.getEntity();

            //origresponseText=readContent(response);
        }
        catch (ClientProtocolException e) 
        {
            // TODO Auto-generated catch block
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
        }
        return null;
    }

and here is my servlet code

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
    Enumeration paramNames = request.getParameterNames();
    String params[] = new String[7];
    int i=0;

    while(paramNames.hasMoreElements())
    {
        String paramName = (String) paramNames.nextElement();
        System.out.println(paramName);


        String[] paramValues = request.getParameterValues(paramName);
        params[i] = paramValues[0];

        System.out.println(params[i]);

        i++;
    }

}
halfer
  • 19,824
  • 17
  • 99
  • 186
Bhargav Thanki
  • 4,924
  • 2
  • 37
  • 43

3 Answers3

6

When I read the already mentioned Google post about best practices doing HTTP requests in newer versions of Android, I thought somebody was kidding me. HttpURLConnection is really a nightmare to use, compared to almost any other way to communicate with HTTP servers (apart from direct Socket communication).

I didn't find a really slim library for Android to do the heavy lifting, so I wrote my own. You can find it at DavidWebb including a list of alternative libraries which I found (unfortunately) after developing the library.

Your code would look more or less like this:

public void testPostToUrl() throws Exception {
    String[] values = new String[3];

    Webb webb = Webb.create();
    Response<String> response = webb
            .post("http://www.example.com/abc.php")
            .param("param1", values[0])
            .param("param2", values[1])
            .param("param3", values[2])
            .asString();

    assertEquals(200, response.getStatusCode());
    assertNotNull(response.getBody());
    assertTrue(response.getBody().contains("my expected result"));
}

public void testPostToUrlShorter() throws Exception {
    String[] values = new String[3];

    Webb webb = Webb.create();
    String result = webb
            .post("http://www.example.com/abc.php")
            .param("param1", values[0])
            .param("param2", values[1])
            .param("param3", values[2])
            .ensureSuccess()
            .asString()
            .getBody();

    assertTrue(result.contains("my expected result"));
}
hgoebl
  • 12,637
  • 9
  • 49
  • 72
1

You should absolutely be using HttpUrlConnection:

For Gingerbread and better, HttpURLConnection is the best choice... New applications should use HttpURLConnection...

--Google (circa. 2011)

However, there is no easy way just to "switch". The APIs are totally different. You are going to have to rewrite your networking code. There are perfect examples in the documentation on how to submit a GET and POST requests as well as in the SDK sample apps.

Community
  • 1
  • 1
Jeffrey Mixon
  • 12,846
  • 4
  • 32
  • 55
  • I saw that already but I dont know how to add parameters in post method while using HttpUrlConnection – Bhargav Thanki Nov 12 '14 at 23:45
  • 1
    For what it's worth, I have a lot of truck with the statement issued by Google on that. HttpUrlConnection is great but there is a lot of mechanics involved with constructing a URL with parameters etc. HttpClient was built specifically to allow much more fine grain control over how an HTTP connection is utilized. I think Google is attempting to get away from a library they bundled and have no clean upgrade path on. – Dave G Nov 12 '14 at 23:54
0

You don't have to switch, you can continue using apache's library like I described in this answer. There are really no downsides to continue using apache's library - it's only google's marketing.

Community
  • 1
  • 1
Jehy
  • 4,729
  • 1
  • 38
  • 55