3
2015-07-11 21:01:08 +08:00
private static String httpRequest(String url, String requestMethod, String postParameters) {
StringBuilder resultString = new StringBuilder();
HttpURLConnection connection = null;
try {
URL urlGet = new URL(url);
// 真正连接在调用http.connect()时;
connection = (HttpURLConnection) urlGet.openConnection();
// 连接超时
connection.setConnectTimeout(CONNECT_TIMEOUT);
// 读取超时 --服务器响应比较慢,增大时间
connection.setReadTimeout(READ_TIMEOUT);
// 设置Http请求method
connection.setRequestMethod(requestMethod);
connection.setDoOutput(true);
connection.setDoInput(true);
if (postParameters != null && requestMethod.equalsIgnoreCase(HTTP_METHOD_POST)) { // Post时调用
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(postParameters.getBytes("UTF-8").length));
// 隐式调用 connection.connect();
OutputStream out = connection.getOutputStream();
out.write(postParameters.getBytes(DEFAULT_CHARSET));
out.flush();
out.close();
}
// 隐式调用 connection.connect();
InputStream in = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString;
while ((valueString = read.readLine()) != null) {
resultString.append(valueString);
}
in.close();
} catch (IOException e) {
LOGGER.error("Https请求出错!", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
return resultString.toString();
}