---------
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public static final Logger logger = Logger.getLogger(HttpRequestUtils.class);
public static final String POST = "POST";
public static final String GET = "GET";
public static final String PUT = "PUT";
public static final String DELETE = "DELETE";
public static final String HEAD = "HEAD";
private static final int CONNECT_TIMEOUT = 30000;
private static final int READ_TIMEOUT = 30000;
/**
* 原生方法通过GET|POST方式请求
* @param urlString
* @param method
* @param params
* @return
*/
public static String getResponseContent(String urlString, String method, List params){
StringBuilder responseBody = new StringBuilder();
try{
if(params != null && method == GET){
urlString = urlString.concat("?");
urlString = urlString.concat(getQueryString(params));
}
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setRequestMethod(method);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
if(params != null && method == POST){
OutputStream os = connection.getOutputStream();
// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
// writer.write(getQueryString(params));
// writer.flush();
// writer.close();
// os.close();
DataOutputStream out = new DataOutputStream(os);
out.writeBytes(getQueryString(params));
out.flush();
out.close();
}
// 读取响应
int responseCode = connection.getResponseCode();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
line = new String(line.getBytes(), "UTF-8");
responseBody.append(line);
}
reader.close();
// 断开连接
connection.disconnect();
}catch (Exception e){
logger.error(e);
e.printStackTrace();
}
return responseBody.toString();
}
private static String getQueryString(List params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params){
if (first){
first = false;
} else {
result.append("&");
}
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(),"UTF-8"));
}
return result.toString();
}