Try it:
public static String executePostHttpRequest(final String path, Map<String, String> params) throws ClientProtocolException, IOException {
String result = null;
HttpURLConnection urlConnection = null;
try {
String postData = getQuery(params);
byte[] postDataBytes = postData.getBytes("UTF-8");
URL url = new URL(path);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("charset", "UTF-8");
urlConnection.setRequestProperty("Content-Length", Integer.toString(postDataBytes.length));
OutputStream out = urlConnection.getOutputStream();
out.write(postDataBytes);
out.close();
result = readStream(urlConnection.getInputStream());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result;
}
Where:
private static String getQuery(Map<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean haveData = params != null && params.size() > 0;
if (haveData) {
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()){
String value = entry.getValue();
if (value != null) {
if (first) {
first = false;
} else {
result.append("&");
}
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value, "UTF-8"));
}
}
}
return result.toString();
}
P.S. I didn't move hard-coded strings to constants for better understanding.