http核心类 package com.eshore.expert.utils;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnecti
package com.eshore.expert.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.eshore.expert.vo.ResultExper; /** * HTTP Client ��ʵ�� * @author eric * */ public class Httplient { /** * 对象转json * @param obj * @return */ public static String Object2Json(Object obj){ JSONObject json = JSONObject.fromObject(obj);//将java对象转换为json对象 String str = json.toString();//将json对象转换为字符串 return str; } /** * 对象转json 数组 ["":""] * @param obj * @return */ public static String objecttoJson(Object obj){ JSONArray array=JSONArray.fromObject(obj); String strArray=array.toString(); return strArray; } /** * 发送请求(专家抽取) * @param url 请求路径 * @param token 密匙 (可为空) * @param data 请求数据(json) * @return 返回true或者false */ public static Map ExperExtraction(String url,String token,String data) throws KeyManagementException, NoSuchAlgorithmException, IOException{ Maphttp辅助类map = new HashMap (); map.put("Authorization",token ); byte[] json= data.getBytes("utf-8"); map.put("Content-Type", "application/json"); HTTPResponse request = Httplient.request(url,json,"POST",map); //发生post请求 ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream in = request.getInputStream(); byte[] b = new byte[1024]; int len =0; while((len=in.read(b))>0){ bos.write(b,0,len); } in.close(); request.close(); //返回数据 并进行对象化 System.err.print("返回的数据"+new String(bos.toByteArray(),"utf-8")); com.alibaba.fastjson.JSONObject parseObjects = com.alibaba.fastjson.JSONObject.parseObject(new String(bos.toByteArray(),"utf-8")); //获取json 数据转为 json对象 ResultExper studs = (ResultExper) com.alibaba.fastjson.JSONObject.toJavaObject(parseObjects,ResultExper.class); //json 对象转为 实体类 if(studs.getResultCode().equals("0")) { String addurl = studs.getData().getAddurl(); map.put("200", addurl); }else{ map.put("500", studs.getResultMsg()); } return map; } /** * 获取token * @param url 请求路径 * @param userName 账号 * @param passWord 密码 * @return 密匙 */ public static String getTokens(String url,String userName,String passWord) throws KeyManagementException, NoSuchAlgorithmException, UnsupportedEncodingException, IOException{ Map maps = new HashMap (); String json ="{\"userName\":\""+userName+"\",\"userPwd\":\""+passWord+"\"}"; maps.put("Content-Type", "application/json;charset:utf-8;"); HTTPResponse res = Httplient.request(url,json.getBytes("utf-8"),"POST",maps); ByteArrayOutputStream boss = new ByteArrayOutputStream(); InputStream ins = res.getInputStream(); byte[] bs = new byte[1024]; int lens =0; while((lens=ins.read(bs))>0){ boss.write(bs,0,lens); } ins.close(); res.close(); System.err.println("token令牌"+new String(boss.toByteArray(),"utf-8")); com.alibaba.fastjson.JSONObject parseObject = com.alibaba.fastjson.JSONObject.parseObject(new String(boss.toByteArray(),"utf-8")); //boos给转换为json对象 ResultExper stud = (ResultExper) com.alibaba.fastjson.JSONObject.toJavaObject(parseObject,ResultExper.class); //把json对象转换为对象 if(stud.getResultSuccess().equals("1")){ return null; } return stud.getResultMsg(); //获取token; } /** * http 请求发送 * @param urlSring 请求链接 * @param data 请求数据(把字符串转为字节数组) * @param method 请求方法 * @param headers 请求头数据 * @return * @throws NoSuchAlgorithmException * @throws KeyManagementException * @throws IOException */ public static HTTPResponse request(String urlSring,byte[] data,String method,Map headers) throws NoSuchAlgorithmException, KeyManagementException, IOException{ if(isSSL(urlSring)){ HttpsURLConnection.setDefaultHostnameVerifier(new Httplient().new NullHostNameVerifier()); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } URL url = new URL(urlSring); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method);// POST GET PUT DELETE conn.setConnectTimeout(130000);// conn.setReadTimeout(130000); conn.setDoInput(true); if(headers!=null){ for(Entry e : headers.entrySet()){ conn.addRequestProperty(e.getKey(), e.getValue()); } } if("post".equalsIgnoreCase(method)){ conn.setDoOutput(true); } try{ conn.connect(); if(data!=null&&data.length>0){ OutputStream out = conn.getOutputStream(); out.write(data); out.close(); } InputStream in = conn.getInputStream(); return new Response(200, in,conn); }catch(Exception e){ return new Response(500, conn.getErrorStream(),conn); } } /** * 把map 转换为jsonString * @param map * @return */ public static String mapToString(Map map){ if(map==null)return ""; StringBuilder sb = new StringBuilder(); sb.append("{"); boolean isFirst =true; for(Entry entry : map.entrySet()){ if(isFirst){ isFirst=false; }else{ sb.append(","); } sb.append('"').append(entry.getKey()).append('"').append(':').append('"').append(entry.getValue()).append('"'); } sb.append("}"); return sb.toString(); } /** * * @param url * @return */ public static boolean isSSL(String url){ if(url.trim().toLowerCase().startsWith("https"))return true; return false; } static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { //@Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } //@Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } //@Override public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } } }; public class NullHostNameVerifier implements HostnameVerifier { /* * (non-Javadoc) * * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, * javax.net.ssl.SSLSession) */ //@Override public boolean verify(String arg0, SSLSession arg1) { // TODO Auto-generated method stub return true; } } }
package com.eshore.expert.utils; import java.io.InputStream; public interface HTTPResponse { int getStatus(); InputStream getInputStream(); void close(); } package com.eshore.expert.utils; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; public class Response implements HTTPResponse { InputStream in ; int status=200; HttpURLConnection conn; public Response(int status ,InputStream in,HttpURLConnection conn){ this.in=in; this.status=status; this.conn=conn; } @Override public int getStatus() { // TODO Auto-generated method stub return status; } @Override public InputStream getInputStream() { // TODO Auto-generated method stub return in; } @Override public void close() { // TODO Auto-generated method stub conn.disconnect(); } }调用函数发送请求并接受实体数据
String object2Json = Httplient.Object2Json(queryProect); //对象转json logger.info("发送去门禁系统" + object2Json); Boolean experExtraction = this.ExperExtraction(url, object2Json); //调用函数发送请求 /** * url 地址 * data 为json数据 */ public Boolean ExperExtraction(String url, String data) throws KeyManagementException, NoSuchAlgorithmException, IOException { Boolean flag = false; Mapmap = new HashMap (); //请求头 map.put("Content-Type", "application/json"); byte[] json = data.getBytes("utf-8"); HTTPResponse request = Httplient.request(url, json, "POST", map); // 发生post请求 ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream in = request.getInputStream(); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b)) > 0) { bos.write(b, 0, len); } in.close(); request.close(); logger.info("门禁返回数据" + new String(bos.toByteArray(), "utf-8")); JSONObject parseObjects = JSONObject.parseObject(new String(bos .toByteArray(), "utf-8")); // 获取json 数据转为 json对象 ResultExper studs = (ResultExper) JSONObject.toJavaObject(parseObjects, ResultExper.class); // json 对象转为 实体类,其中ResultExper为需要转换的类 Object object = parseObjects.get("IsSuccess"); if (object.equals("200")) { flag = true; } return flag; }