下面这段HttpProxyUtil HTTP请求工具类源码,是以URLConnection方式连接Get,Post方式请求,另外本站中另有HttpClient方式请求HTTP,有兴趣的自行搜索查看
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * HTTP请求代理类 * * @author X-rapido * @description 发送Get Post请求 */ public class HttpProxyUtil { private static Logger logger = Logger.getLogger(HttpProxyUtil.class); /** * 使用URLConnection进行GET请求 * @param api_url * @return */ public static String sendGet(String api_url) { return sendGet(api_url, "", "utf-8"); } /** * 使用URLConnection进行GET请求 * @param api_url * @param param * @return */ public static String sendGet(String api_url, String param) { return sendGet(api_url, param, "utf-8"); } /** * 使用URLConnection进行GET请求 * @param api_url 请求路径 * @param param 请求格式有name1=value1&name2=value2、json、xml、map或其他形式,具体要看接收方的取值, 可以为空 * @param charset 字符集 * @return */ public static String sendGet(String api_url, String param, String charset) { StringBuffer buffer = new StringBuffer(); try { // 判断有无参数,若是拼接好的url,就不必再拼接了 if(param!=null && !"".equals(param)){ api_url = api_url + "?" + param; } logger.info("请求的路径是:" + api_url); URL realUrl = new URL(api_url); // 打开联接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setConnectTimeout(12000); //设置连接主机超时(单位:毫秒) conn.setReadTimeout(12000); // 设置从主机读取数据超时(单位:毫秒) conn.connect(); // 建立实际的联接 // 定义 BufferedReader输入流来读取URL的相应 try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset))) { String line; while ((line = in.readLine()) != null) { // buffer.append("\n"+line); buffer.append(line); } } } catch (Exception e) { logger.error("发送GET请求出现异常! " + e.getMessage()); e.printStackTrace(); } logger.info("响应返回数据:" + buffer.toString()); return buffer.toString(); } /** * 使用URLConnection进行POST请求 * @param api_url 请求路径 * @param param 请求格式有name1=value1&name2=value2、json、xml、map或其他形式,具体要看接收方的取值,最好不为空 * @return */ public static String sendPost(String api_url, String param) { return sendPost(api_url, param , "utf-8"); } /** * 使用URLConnection进行POST请求 * @param api_url 请求路径 * @param param 请求格式有name1=value1&name2=value2、json、xml、map或其他形式,具体要看接收方的取值,最好不为空 * @param charset 字符集 * @return */ public static String sendPost(String api_url, String param, String charset) { StringBuffer buffer = new StringBuffer(); try { logger.info("请求的路径是:"+ api_url+",参数是:" + param); URL realUrl = new URL(api_url); // 打开联接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setConnectTimeout(12000); //设置连接主机超时(单位:毫秒) conn.setReadTimeout(12000); // 设置从主机读取数据超时(单位:毫秒) // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 try (PrintWriter out = new PrintWriter(conn.getOutputStream())) { out.print(param); // 发送请求参数 out.flush();// flush输出流的缓冲 } // 定义 BufferedReader输入流来读取URL的相应,得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别 try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset))) { String line; while ((line = in.readLine()) != null) { // buffer.append("\n"+line); buffer.append(line); } } } catch (Exception e) { logger.error("发送POST请求出现异常! " + e.getMessage()); e.printStackTrace(); } logger.info("响应返回数据:" + buffer.toString()); return buffer.toString(); } public static CloseableHttpClient createSSLClientDefault() throws Exception { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new AllTrustStrategy()).build(); SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom().setSSLSocketFactory(sslSf).build(); } // 加载证书 private static class AllTrustStrategy implements TrustStrategy { public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } } /** * 支持https请求 * @param url * @param param * @return * @throws Exception */ public static String sendHttpClientPost(String url, Map<String, String> param) throws Exception{ CloseableHttpClient httpClient = createSSLClientDefault(); HttpPost httpPost = null; CloseableHttpResponse response = null; String result = ""; try { // 发起HTTP的POST请求 httpPost = new HttpPost(url); List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } logger.info("http请求地址:"+url+",参数:"+paramList.toString()); // UTF8+URL编码 httpPost.setEntity(new UrlEncodedFormEntity(paramList, Consts.UTF_8)); httpPost.setConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build()); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == statusCode){ // 如果响应码是200 } result = EntityUtils.toString(entity); logger.info("状态码:"+statusCode+",响应信息:"+result); } finally { if (response != null) {response.close();} if (httpPost != null) {httpPost.releaseConnection();} httpClient.close(); } return result; } }