Instead of using HttpURLConnection why don't you use HttpClient class with HttpPost class. This way you avoid the tension of URL encoding. Below is an example on how to it:
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR URL);
try {
ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PARAMETER1, VALUE1));
nameValuePairs.add(new BasicNameValuePair(PARAMETER2, VALUE2));
...
nameValuePairs.add(new BasicNameValuePair(PARAMETERn, VALUEn));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
EDIT:
String result = "";
URL url = new URL(YOUR URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PARAMETER1, VALUE1));
nameValuePairs.add(new BasicNameValuePair(PARAMETER2, VALUE2));
...
nameValuePairs.add(new BasicNameValuePair(PARAMETERn, VALUEn));
//Send request
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getUrlParameters(params));
writer.flush();
writer.close();
os.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = br.readLine()) != null) {
response.append(line);
response.append('\r');
}
r.close();
result = response.toString();
conn.disconnect();
Code for getUrlParameters() method:
private String getUrlParameters(List<NameValuePair> params) throws UnsupportedEncodingException{
StringBuilder parameter = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
parameter.append(URLEncoder.encode(pair.getName(), "UTF-8"));
parameter.append("=");
parameter.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
parameter.append("&");
}
return parameter.toString().substring(0, parameter.length()-2);
}
But my initial approach is very easy to implement and has never failed me not even once. As for which approach you wish to use totally up to you, weather you go with HttpURLConnection (Android recommended approach) or the other one.