1、HttpClient
package com.dtb.admin.util; import org.apache.http.NameValuePair; 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.client.utils.URIBuilder; 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.util.EntityUtils; import javax.net.ssl.*; import java.io.*; import java.net.URI; import java.net.URL; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8"); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } public static final String GET = "GET"; public static final String POST = "POST"; public static final String HEAD = "HEAD"; public static final String OPTIONS = "OPTIONS"; public static final String PUT = "PUT"; public static final String DELETE = "DELETE"; public static final String TRACE = "TRACE"; private static Map<String, SSLSocketFactory> SSLSocketFactoryPool = new ConcurrentHashMap<>();//签名缓存 private static Map<String, URL> URLPool = new ConcurrentHashMap<>();//URL链接缓存 /** * 处理https GET/POST请求 * 请求地址、请求方法、参数 * @param requestUrl 请求参数(为使用连接池处理,请不要在url中携带参数,并且保证同接口url唯一) * @param requestMethod GET/POST请求 等 * @param param 参数 * @return * @throws Exception */ public static String httpsRequest(String requestUrl,String requestMethod, Map<String, Object> param) throws Exception{ if (!requestUrl.startsWith("https")) { if ("GET".equals(requestMethod)) { return URLConnectionUtil.doGet(requestUrl, param); }else{ return URLConnectionUtil.doPost(requestUrl, param); } } requestUrl = requestUrl.trim(); StringBuffer outputStrBf = new StringBuffer(); //解析参数 if (param != null&¶m.size()>0&&!GET.equals(requestMethod)) { Set<Entry<String, Object>> entrySet = param.entrySet(); Iterator<Entry<String, Object>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Entry<String, Object> next = iterator.next(); if (next.getValue() != null) { outputStrBf.append("&"+next.getKey()+"="+next.getValue().toString()); } } }else if (param != null&&GET.equals(requestMethod)) { Set<Entry<String, Object>> entrySet = param.entrySet(); Iterator<Entry<String, Object>> iterator = entrySet.iterator(); boolean isStart = true; while (iterator.hasNext()) { Entry<String, Object> next = iterator.next(); if (next.getValue() != null) { if (!requestUrl.contains("?")&&isStart) { outputStrBf.append("?"+next.getKey()+"="+next.getValue().toString()); isStart = false; }else{ outputStrBf.append("&"+next.getKey()+"="+next.getValue().toString()); } } } } StringBuffer buffer=null; URL url= null; SSLSocketFactory ssf= null; try{ if (URLPool.size()>0&&URLPool.containsKey(requestUrl)) { url = URLPool.get(requestUrl); ssf = SSLSocketFactoryPool.get(requestUrl); }else{ //创建SSLContext SSLContext sslContext=SSLContext.getInstance("SSL"); TrustManager[] tm={new MyX509TrustManager()}; //初始化 sslContext.init(null, tm, new java.security.SecureRandom());; //获取SSLSocketFactory对象 ssf=sslContext.getSocketFactory(); if (GET.equals(requestMethod)) { url=new URL(requestUrl+outputStrBf.toString()); }else{ url=new URL(requestUrl); } } HttpsURLConnection conn =(HttpsURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod(requestMethod); //设置当前实例使用的SSLSoctetFactory conn.setSSLSocketFactory(ssf); conn.connect(); if (!GET.equals(requestMethod)) { //往服务器端写内容 if(null!=outputStrBf){ OutputStream os=conn.getOutputStream(); os.write(outputStrBf.toString().getBytes("utf-8")); os.close(); } } //读取服务器端返回的内容 InputStream is=conn.getInputStream(); InputStreamReader isr=new InputStreamReader(is,"utf-8"); BufferedReader br=new BufferedReader(isr); buffer=new StringBuffer(); String line=null; while((line=br.readLine())!=null){ buffer.append(line); } //进行链接缓存 SSLSocketFactoryPool.put(requestUrl, ssf); URLPool.put(requestUrl, url); }catch(Exception e){ e.printStackTrace(); } return buffer==null?"":buffer.toString(); } } class MyX509TrustManager implements 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; } }
2、Page
import java.util.ArrayList; import java.util.List; import java.util.Map; public class Page { private int total; //总记录数 private List<Map<String, Object>> list; private int pageNo; //当前页号 private int pageSize;//一页记录数 private int maxPageNo; //最大页数 private List<Object> pageNoList = new ArrayList<>(); public void setMaxPageNo(int maxPageNo) { this.maxPageNo = maxPageNo; } public void setPageNoList(List<Object> pageNoList) { this.pageNoList = pageNoList; } public int getMaxPageNo() { maxPageNo = total / pageSize; if(total % pageSize > 0 || total == 0){ maxPageNo += 1; } return maxPageNo; } public List<Object> getPageNoList(){ getMaxPageNo(); pageNoList = new ArrayList<Object>(); if(pageNo <= 4 && maxPageNo <= pageNo+4){ for(int i=1;i<=maxPageNo;i++){ pageNoList.add(i); } }else if(pageNo <=4 && maxPageNo > pageNo+4){ for(int i=1;i<=9;i++){ pageNoList.add(i); } }else if(pageNo > 4 && maxPageNo <= pageNo+4 && pageNo != 5 && pageNo != 6 && pageNo != 7 && pageNo != 8){ for(int i=maxPageNo-9;i<=maxPageNo;i++){ pageNoList.add(i); } }else if(pageNo > 4 && maxPageNo > pageNo+4 ){ for(int i=pageNo-4;i<=pageNo+4;i++){ pageNoList.add(i); } }else { //处理5 5,6 6,7 7,8 8 (页码页数 最大页码)类型的数据 for(int i=1;i<=maxPageNo;i++){ pageNoList.add(i); } } //处理5 5,6 6,7 7,8 8 (页码页数 最大页码)类型的数据 if (pageNoList.size()>0) { for(int i = 0; i < pageNoList.size();i++ ){ if (Integer.valueOf(String.valueOf(pageNoList.get(i))) < 0) { pageNoList.remove(i); } } } return pageNoList; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<Map<String, Object>> getList() { return list; } public void setList(List<Map<String, Object>> list) { this.list = list; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } }
3、实现方法
url是路径,map是参数
public Page getRomoteSxt(String url, Map<String, Object> map) { Page page = null; String resultString = null; try { resultString = HttpClientUtil.httpsRequest(url, HttpClientUtil.POST, map); JSONObject json = JSON.parseObject(resultString); if (json.getBoolean("success")) { page = json.getObject("data", Page.class); } } catch (Exception e) { e.printStackTrace(); } return page; }