package com.yfcl.iot.util.httpClient; 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.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.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.ContentType; 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.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; 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.Map.Entry; import java.util.Set; /** * http客户端 * @author:yfcl */ public class HttpClient { private static final int SOCKET_TIME_OUT = 60000; // 设置读取超时 private static final int CONNECT_TIME_OUT = 60000; // 设置连接超时 /** * post请求传输map数据 * * @param url * @param map * @param encoding * @return * @throws ClientProtocolException * @throws IOException */ public static String sendPostDataByMap(String url, Map<String, String> map, String encoding) throws ClientProtocolException, IOException { String result = ""; // 创建httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建post方式请求对象 HttpPost httpPost = new HttpPost(url); // 装填参数 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (map != null) { for (Entry<String, String> entry : map.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } // 设置参数到请求对象中 httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, encoding)); // 设置header信息 // 指定报文头【Content-type】、【User-Agent】 httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = httpClient.execute(httpPost); // 获取结果实体 // 判断网络连接状态码是否正常(0--200都数正常) if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(response.getEntity(), "utf-8"); } // 释放链接 response.close(); return result; } public String sendPost(String url, String data) { String response = null; try { CloseableHttpClient httpclient = null; CloseableHttpResponse httpresponse = null; try { httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", "UTF-8")); httppost.setEntity(stringentity); httpresponse = httpclient.execute(httppost); response = EntityUtils .toString(httpresponse.getEntity()); } finally { if (httpclient != null) { httpclient.close(); } if (httpresponse != null) { httpresponse.close(); } } } catch (Exception e) { e.printStackTrace(); } return response; } public String modifyAndSave(String url, org.springframework.http.HttpEntity<String> entity, String method) { //String url = reDFWUrl(query); String obj = ""; try { RestTemplate template = new RestTemplate(); obj = template.postForObject(url, entity, String.class); } catch (Exception e) { e.printStackTrace(); } return obj; } /** * post请求传输json数据 * * @param url * @param json * @param encoding * @return * @throws ClientProtocolException * @throws IOException */ public static String sendPostDataByJson(String url, String json, String encoding) throws ClientProtocolException, IOException { String result = ""; // 创建httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建post方式请求对象 HttpPost httpPost = new HttpPost(url); // 设置参数到请求对象中 StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON); stringEntity.setContentEncoding("UTF-8"); httpPost.setEntity(stringEntity); // 执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = httpClient.execute(httpPost); // 获取结果实体 // 判断网络连接状态码是否正常(0--200都数正常) if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(response.getEntity(), "utf-8"); } // 释放链接 response.close(); return result; } /** * get请求传输数据 * * @param url * @param encoding * @return * @throws ClientProtocolException * @throws IOException */ public String sendGetData(String url, String encoding) throws ClientProtocolException, IOException { String result = ""; // 创建httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建get方式请求对象 HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Content-type", "application/json"); // 通过请求对象获取响应对象 CloseableHttpResponse response = httpClient.execute(httpGet); // 获取结果实体 // 判断网络连接状态码是否正常(0--200都数正常) if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(response.getEntity(), "utf-8"); } // 释放链接 response.close(); return result; } /** * 创建一个SSL信任所有证书的httpClient对象 * @return */ public static CloseableHttpClient createSSLInsecureClient() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 默认信任所有证书 @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); // AllowAllHostnameVerifier: 这种方式不对主机名进行验证,验证功能被关闭,是个空操作(域名验证) SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return HttpClients.custom().setSSLSocketFactory(sslcsf).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } //如果创建失败,就创建一个默认的Http的连接 return HttpClients.createDefault(); } /** * 无需本地证书keyStore的SSL https带参数请求 * post K - V 格式的数据 * @param url * @param params * @param headers * @return */ public static String postSSLParams(String url, Map<String, Object> params, Map<String, Object> headers) { //创建一个信任的连接 CloseableHttpClient httpClient = HttpClient.createSSLInsecureClient(); //发送请求的实体类 HttpPost httpPost = new HttpPost(url); //接收返回值 StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { // 设置客户端请求的头参数getParams已经过时,现在用requestConfig对象替换 httpPost.setConfig(getRequestConfig()); //设置请求的头信息 Set<String> keys = headers.keySet(); for (String key : keys) { httpPost.setHeader(key, headers.get(key).toString()); } //这个是设置请求的类型,这个可能需要重点注意下,需要看对方接收的是什么 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); //添加参数, 设置编码格式 httpPost.setEntity(new UrlEncodedFormEntity( createParam(params) , Charset.forName("utf-8"))); //发送请求 HttpResponse response = httpClient.execute(httpPost); //接收返回值 HttpEntity httpEntity = response.getEntity(); //返回值处理 br = new BufferedReader(new InputStreamReader(httpEntity.getContent(),"utf-8")); String s = null; while((s=br.readLine())!=null){ sb.append(s); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + "utf-8"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { throw new RuntimeException("读取流文件异常",e); }catch (Exception e) { throw new RuntimeException("通讯未知系统异常",e); }finally{ if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } /** * 设置请求的参数值 * @return */ private static RequestConfig getRequestConfig() { return RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build(); } /** * 设置参数列表 * @param param * @return */ private static List<NameValuePair> createParam(Map<String, Object> param) { List<NameValuePair> nvps = new ArrayList <NameValuePair>(); if(param != null) { for(String k : param.keySet()) { nvps.add(new BasicNameValuePair(k, param.get(k).toString())); } } return nvps; } }
HttpClient
最新推荐文章于 2024-01-09 15:25:58 发布