首页 > 代码库 > JAVA API about HTTP 2
JAVA API about HTTP 2
1 import java.io.IOException; 2 import java.nio.charset.Charset; 3 import java.security.KeyManagementException; 4 import java.security.KeyStoreException; 5 import java.security.NoSuchAlgorithmException; 6 import java.util.ArrayList; 7 import java.util.HashMap; 8 import java.util.List; 9 import java.util.Map; 10 11 import javax.net.ssl.SSLContext; 12 13 import org.apache.commons.lang.StringUtils; 14 import org.apache.http.HttpEntity; 15 import org.apache.http.NameValuePair; 16 import org.apache.http.client.config.RequestConfig; 17 import org.apache.http.client.entity.UrlEncodedFormEntity; 18 import org.apache.http.client.methods.CloseableHttpResponse; 19 import org.apache.http.client.methods.HttpGet; 20 import org.apache.http.client.methods.HttpPost; 21 import org.apache.http.client.utils.URIBuilder; 22 import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 23 import org.apache.http.conn.ssl.SSLContextBuilder; 24 import org.apache.http.conn.ssl.TrustStrategy; 25 import org.apache.http.entity.StringEntity; 26 import org.apache.http.impl.client.CloseableHttpClient; 27 import org.apache.http.impl.client.HttpClientBuilder; 28 import org.apache.http.message.BasicNameValuePair; 29 import org.apache.http.util.EntityUtils; 30 31 import org.slf4j.Logger; 32 import org.slf4j.LoggerFactory; 33 34 import com.fasterxml.jackson.databind.ObjectMapper; 35 36 37 public class HttpClient { 38 39 private final static String ENCODE = "utf-8"; 40 41 private final static Charset CHARSET = Charset.forName("utf-8"); 42 43 private final static int SOCKET_TIME_OUT = 12000; 44 45 private final static int SOCKET_CONNECT_OUT = 12000; 46 47 private final static int CONNECTION_REQUEST_OUT = 12000; 48 49 private static RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT) 50 .setConnectTimeout(SOCKET_CONNECT_OUT).setConnectionRequestTimeout(CONNECTION_REQUEST_OUT).build(); 51 52 private static ObjectMapper objectMapper = new ObjectMapper(); 53 54 private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class); 55 56 @SuppressWarnings("deprecation") 57 public static SSLConnectionSocketFactory sslInit() { 58 SSLContext sslContext = null; 59 try { 60 sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { 61 // 信任所有 62 public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { 63 return true; 64 } 65 }).build(); 66 67 } catch (KeyManagementException e) { 68 e.printStackTrace(); 69 } catch (NoSuchAlgorithmException e) { 70 e.printStackTrace(); 71 } catch (KeyStoreException e) { 72 e.printStackTrace(); 73 } 74 return new SSLConnectionSocketFactory(sslContext); 75 } 76 77 78 79 80 /** 81 * @Description post请求函数 82 * @param scheme http/https 83 * @param host 请求域名 84 * @param path 请求路径 85 * @param params URL请求参数 86 * @param jsonBody HTTP请求BODY 87 * @param headers HTTP请求头部 88 * @return 89 */ 90 public static HashMap post(String scheme, String host, String path, Map<String, String> params, String jsonBody, Map<String, String> headers) { 91 HashMap resultMap = new HashMap(); 92 CloseableHttpClient closeableHttpClient = null; 93 try { 94 SSLConnectionSocketFactory sslsf = sslInit(); 95 closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig).setSSLSocketFactory(sslsf).build(); 96 97 //添加URL参数 98 List<NameValuePair> values = new ArrayList<NameValuePair>(); 99 if (params != null && !params.isEmpty()) {100 for (String s : params.keySet()) {101 values.add(new BasicNameValuePair(s, params.get(s)));102 }103 }104 //创建URI105 java.net.URI uri = new URIBuilder()106 .setScheme(scheme)107 .setHost(host)108 .setPath(path)109 .setParameters(values)110 .build();111 112 HttpPost httpPost = new HttpPost(uri);113 //添加头部114 if (headers != null && !headers.isEmpty()) {115 for (String s : headers.keySet()) {116 httpPost.addHeader(s, headers.get(s));117 }118 }119 //添加URL参数120 /*if (params != null && !params.isEmpty()) {121 List<NameValuePair> values = new ArrayList<NameValuePair>();122 for (String s : params.keySet()) {123 values.add(new BasicNameValuePair(s, params.get(s)));124 }125 httpPost.setEntity(new UrlEncodedFormEntity(values, ENCODE));126 }*/127 128 //添加请求BODY129 if (jsonBody != null) {130 httpPost.setEntity(new StringEntity(jsonBody, Charset.forName("utf-8")));131 }132 133 LOG.info("HTTP Request URI:{}",httpPost.getURI().toString());134 LOG.info("HTTP Request Body: {}",jsonBody);135 136 //发出请求137 CloseableHttpResponse response = closeableHttpClient.execute(httpPost);138 HttpEntity entity = response.getEntity();139 String content = EntityUtils.toString(entity, ENCODE);140 LOG.info("HTTP Response:{}",content);141 142 if(StringUtils.isNotBlank(content)){143 resultMap = objectMapper.readValue(content, HashMap.class); 144 }145 } catch (Exception e) {146 LOG.info("Error msg:[{}]",e.getMessage());147 e.printStackTrace();148 } finally {149 try {150 if (closeableHttpClient != null) {151 closeableHttpClient.close();152 }153 } catch (IOException e) {154 e.printStackTrace();155 }156 }157 return resultMap;158 }159 160 161 162 163 /**164 * @Description http get请求函数165 * @param scheme http/https166 * @param host 域名167 * @param path 资源路径168 * @param params 请求参数169 * @param headers 请求头部170 * @return171 */172 public static HashMap get(String scheme, String host, String path, Map<String, String> params, Map<String, String> headers) {173 HashMap resultMap = new HashMap();174 CloseableHttpClient closeableHttpClient = null;175 try {176 SSLConnectionSocketFactory sslsf = sslInit();177 closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig).setSSLSocketFactory(sslsf).build();178 179 //添加URL参数180 List<NameValuePair> values = new ArrayList<NameValuePair>();181 if (params != null && !params.isEmpty()) {182 for (String s : params.keySet()) {183 values.add(new BasicNameValuePair(s, params.get(s)));184 }185 }186 187 //创建URI188 java.net.URI uri = new URIBuilder()189 .setScheme(scheme)190 .setHost(host)191 .setPath(path)192 .setParameters(values)193 .build();194 195 LOG.info("URI is:{}",uri.toString());196 //创建GET请求对象197 HttpGet httpGet = new HttpGet(uri);198 199 //添加头部200 if (headers != null && !headers.isEmpty()) {201 for (String s : headers.keySet()) {202 httpGet.addHeader(s, headers.get(s));203 }204 }205 206 //发出请求207 LOG.info("HTTP Request:{}",httpGet.getURI().toString());208 CloseableHttpResponse response = closeableHttpClient.execute(httpGet);209 HttpEntity entity = response.getEntity();210 String content = EntityUtils.toString(entity, ENCODE);211 LOG.info("HTTP Response:{}",content);212 213 if(StringUtils.isNotBlank(content)){214 resultMap = objectMapper.readValue(content, HashMap.class); 215 }216 } catch (Exception e) {217 LOG.info("Error msg:[{}]",e.getMessage());218 e.printStackTrace();219 } finally {220 try {221 if (closeableHttpClient != null) {222 closeableHttpClient.close();223 }224 } catch (IOException e) {225 e.printStackTrace(); 226 }227 }228 return resultMap;229 }230 231 }
JAVA API about HTTP 2
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。