import java.nio.charset.Charset; import java.util.Map; import com.alibaba.fastjson.JSONObject; public interface HttpService { String doGet(String url, Map<String, String> params); String doPost(String url, Map<String, Object> paramMap); String doPost(String url, JSONObject json); JSONObject sendHttpsRequest(String requestUrl, String requestMethod, String param); String doPosts(String url,Map<String,String> params,Charset character); }
支持https的客户端 import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; /** * 提供给httpsUtils的支持类 * * */ @SuppressWarnings("deprecation") public class SSLClient extends DefaultHttpClient{ public SSLClient() throws Exception{ super(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); } }
import java.nio.charset.Charset; import java.util.Map; import com.alibaba.fastjson.JSONObject; /** */ public interface HttpService { String doGet(String url, Map<String, String> params); String doPost(String url, Map<String, Object> paramMap); String doPost(String url, JSONObject json); JSONObject sendHttpsRequest(String requestUrl, String requestMethod, String param); String doPosts(String url,Map<String,String> params,Charset character); }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; 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.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import com.alibaba.fastjson.JSONObject; import com.ziku.ms.youle.exception.BizException; import com.ziku.ms.youle.service.http.HttpService; import com.ziku.ms.youle.util.SSLClient; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class HttpServiceImpl implements HttpService { @Autowired private HttpClient httpClient; /** * 发送 GET 请求(HTTP),K-V形式 * * @param url * 请求URL * @param params * 请求参数map K-V形式 * @return */ @Override public String doGet(String url, Map<String, String> params) { HttpResponse response = null; String apiUrl = url; StringBuffer param = new StringBuffer(); int i = 0; String responseData = null; try { if (!ObjectUtils.isEmpty(params) && !params.isEmpty()) { for (String key : params.keySet()) { if (i == 0) { param.append("?"); }else { param.append("&"); } param.append(key).append("=").append(URLEncoder.encode(params.get(key), "utf-8")); i++; } apiUrl += param.toString(); } HttpGet httpGet = new HttpGet(apiUrl); response = httpClient.execute(httpGet); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { log.error("HttpServiceImpl-Get,请求URL:{},响应码:{}", url, response.getStatusLine().getStatusCode()); return null; } HttpEntity entity = response.getEntity(); if (entity != null) { responseData = EntityUtils.toString(entity, "UTF-8"); } } catch (SocketTimeoutException ex) { log.warn("[TimeOut]" + url); throw new RuntimeException("SocketTimeoutException连接超时!"); } catch (IOException e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return responseData; } /** * 发送 POST 请求(HTTP),K-V形式 * * @param url * API接口URL * @param params * 参数map * @return */ @Override public String doPost(String url, Map<String, Object> paramMap) { log.debug("HttpServiceImpl.post,请求的url:{},请求参数:{}", url, paramMap); String responseData = null; HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); if (paramMap != null && paramMap.size() > 0) { paramMap.entrySet().forEach(entry -> { params.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue())); }); } try { httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // 设置参数与编码 HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); responseData = EntityUtils.toString(entity); EntityUtils.consume(entity); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { log.error("HttpServiceImpl-post,请求URL:{},响应码:{}", url, response.getStatusLine().getStatusCode()); return null; } } catch (SocketTimeoutException ex) { log.warn("[TimeOut]" + url); throw new RuntimeException("SocketTimeoutException连接超时!"); } catch (Exception ex) { httpPost.abort(); throw new RuntimeException("httpclient异常!", ex); } finally { httpPost.releaseConnection(); } return responseData; } /** * 发送 POST 请求(HTTP),JSON形式 * * @param url * //请求的URL * @param json * //json对象 * * @return */ @Override public String doPost(String url, JSONObject json) { log.info("HttpServiceImpl.post,请求的url:{},请求参数:{}", url, json); String responseData = null; HttpPost httpPost = new HttpPost(url); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); try { HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { log.error("HttpServiceImpl-post,请求URL:{},响应码:{}", url, response.getStatusLine().getStatusCode()); return null; } responseData = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } catch (SocketTimeoutException ex) { log.warn("[TimeOut]" + url); throw new RuntimeException("SocketTimeoutException连接超时!"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("httpclient异常!", e); } finally { httpPost.releaseConnection(); } return responseData; } @Override public JSONObject sendHttpsRequest(String requestUrl, String requestMethod, String param) { log.info("请求URL------>requestUrl:{}", requestUrl); if (StringUtils.isEmpty(requestUrl)) { throw new BizException(StringUtils.EMPTY, "requestUrl不能为空"); } if (StringUtils.isEmpty(requestMethod)) { throw new BizException(StringUtils.EMPTY, "requestMethod不能为空"); } if (!"GET".equalsIgnoreCase(requestMethod) && !"POST".equalsIgnoreCase(requestMethod)) { throw new BizException(StringUtils.EMPTY, "requestMethod只能为GET或者POST"); } JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, new TrustManager[] { tm }, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) { httpUrlConn.connect(); } // 当有数据需要提交时 if (null != param) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(param.getBytes("UTF-8")); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.parseObject(buffer.toString()); } catch (ConnectException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } /** * https发送post请求 * @param url 请求的https地址 * @param params 需要传输的参数,key为参数名,value为对应的值 * @param character 本次请求所采用的字符集编码一般为UTF-8,取值方式为使用枚举:StandardCharsets.UTF_8 * @return * @throws HttpsRequestException 请求底层接口失败 */ @Override public String doPosts(String url,Map<String,String> params,Charset character) { HttpClient httpClient = null; HttpPost httpPost = null; String result = null; try{ //构造访问参数 List<NameValuePair> list = null; if(params!=null){ list = new ArrayList<NameValuePair>(); Set<Entry<String, String>> entrySet = params.entrySet(); for (Entry<String, String> entry : entrySet) { NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(),entry.getValue()); list.add(nameValuePair); } } httpClient = new SSLClient(); httpPost = new HttpPost(url); httpPost.addHeader("Content-Type","application/x-www-form-urlencoded;"+character); httpPost.setHeader("Accept-Charset","utf-8"); StringEntity se = new UrlEncodedFormEntity(list,character); httpPost.setEntity(se); HttpResponse response = httpClient.execute(httpPost); if(response != null){ HttpEntity resEntity = response.getEntity(); if(resEntity != null){ result = EntityUtils.toString(resEntity,character); } } }catch(Exception ex){ ex.printStackTrace(); } return result; } }
本文介绍了一个HTTP服务接口的实现,包括GET和POST请求的方法,同时深入探讨了HTTPS请求的具体实现细节,如证书信任管理及Socket工厂配置。

被折叠的 条评论
为什么被折叠?



