bhargav bhargav - 1 year ago 127
Java Question

how to switch from HttpClient to HttpUrlConnection

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 afterall its good practice to use HttpUrlConnection instead HttpPost.
So I want to convert my HttpPost code to HttpUrlConnectio but dont know how.
So please help me 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);
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();

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
ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
Enumeration paramNames = request.getParameterNames();
String params[] = new String[7];
int i=0;

String paramName = (String) paramNames.nextElement();

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




Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download