Friday, March 2, 2012

UTF-8 Encoding of parameters in POST request

We should consider  encoding of  the parameters  which we sent on  http request.. Otherwise when a parameter  such as in japaneese language then request may not be a successful one .In an http post request we can do it as below.

ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>();
nameValuePairs.add(new BasicNameValuePair("parameter","parameter value"));
URL url = new URL(" url string ");

AbstractHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.addHeader("Date", dateCurrent);
int nResponse = 0;
HttpResponse response = null;
try {
         httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs , "UTF-8"));
         response = httpClient.execute(httpPost);
        nResponse = response.getStatusLine().getStatusCode();
        if (nResponse == HttpURLConnection.HTTP_OK) {
          InputStream instream = response.getEntity().getContent();
                              // Process the stream
        }else if (nResponse == HttpURLConnection.HTTP_UNAUTHORIZED) {
        String res = readStream(response.getEntity().getContent());
        Log.i("Response", res);
                            // Process the error stream.
       }
   }  catch (Exception e) {
 e.printStackTrace();
}
return null;
}

No comments:

Post a Comment