/**
* 简单封装 HTTP 请求工具类
*/
public static String doPost(String requestUrl, Map<String, String> params) throws Exception {
// 获取连接
URL url = new URL(requestUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setConnectTimeout(15 * 1000);
urlConn.setReadTimeout(15 * 1000);
urlConn.setDoOutput(true);
// 格式化请求参数
StringBuffer sb = new StringBuffer();
for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext(); ) {
String name = iter.next();
sb.append(name + "=").append(params.get(name));
if (iter.hasNext()) {
sb.append("&");
}
}
// 向服务端写出请求参数
byte[] b = sb.toString().getBytes(CHARSEST);
urlConn.getOutputStream().write(b, 0, b.length);
urlConn.getOutputStream().flush();
urlConn.getOutputStream().close();
// 获取响应
InputStream in = null;
BufferedReader rd = null;
try {
if (urlConn.getResponseCode() == 200) {
in = urlConn.getInputStream();
} else {
in = urlConn.getErrorStream();
}
rd = new BufferedReader(new InputStreamReader(in, CHARSEST));
String tempLine = rd.readLine();
StringBuffer tempStr = new StringBuffer();
String crlf = System.getProperty("line.separator");
while (tempLine != null) {
tempStr.append(tempLine);
tempStr.append(crlf);
tempLine = rd.readLine();
}
return tempStr.toString();
} finally {
if (rd != null) {
rd.close();
}
if (in != null) {
in.close();
}
}
}