两个系统如何调用接口获取返回值

1.使用场景

两个公司进行合作,但是是两个毫不相关的项目,所以就需要使用http请求远程访问接口获取返回值。

2.如何做到

使用http请求建立连接访问接口获取返回值并解析

调用其他系统接口工具类如下

/**
* @author wangli
* @data 2022/3/24 9:49
* @Description:http请求工具类
 */
public class HttpClientUtils {
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
   private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
   
   private Map<String,String> map;
   
   public HttpClientUtils(Map<String,String> map){
      this.map = map;
   }
   
   /*
    * 根据map获取请求参数
    */
   public String getParam(){
      StringBuilder sb = new StringBuilder();
      
      Set<String> keySet = map.keySet();
      for (String string : keySet) {
         sb.append(string + "=" + map.get(string) + "&");
      }
      
      return sb.toString();
   }
   
    public static String sendGet(String url) {
          
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            //System.out.println("发送get请求********************"+urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            
            connection.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
            connection.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
            
            
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            //建立长连接
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                log.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
           log.error("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
       OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection  conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
            conn.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
            
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("X-APP-KEY", "f4900c0c-39ce-4852-bfcf-595e7b877e31");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(),"utf-8");

            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
                InputStream inputStream = conn.getInputStream();
                 // 定义BufferedReader输入流来读取URL的响应
                 in = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                 String line;
                 while ((line = in.readLine()) != null) {
                     result += line;
                 }
            }else{
               InputStream errorStream = conn.getErrorStream();
               // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(errorStream,"utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                log.error("响应失败:"+conn.getResponseCode()+",响应信息"+conn.getResponseMessage()+",返回信息:"+result);
            }
           
        }catch (Exception e) {
            log.error("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
               log.error("关闭流异常"+ex);
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    /*
     *post请求,参数为json类型
     */
    public static String sendJsonPost(String url, String jsonParam) {
       OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection  conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
            conn.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
            
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(),"utf-8");

            // 发送请求参数
            out.write(jsonParam);
            // flush输出流的缓冲
            out.flush();
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
                InputStream inputStream = conn.getInputStream();
                 // 定义BufferedReader输入流来读取URL的响应
                 in = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                 String line;
                 while ((line = in.readLine()) != null) {
                     result += line;
                 }
            }else{
               log.error("响应失败");
            }
           
        }catch (Exception e) {
            log.error("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
               log.error("关闭流异常"+ex);
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    public static String getBrowserName(String agent) {
         if(agent.indexOf("msie 7")>0){
          return "ie7";
         }else if(agent.indexOf("msie 8")>0){
          return "ie8";
         }else if(agent.indexOf("msie 9")>0){
          return "ie9";
         }else if(agent.indexOf("msie 10")>0){
          return "ie10";
         }else if(agent.indexOf("msie")>0){
          return "ie";
         }else if(agent.indexOf("opera")>0){
          return "opera";
         }else if(agent.indexOf("opera")>0){
          return "opera";
         }else if(agent.indexOf("firefox")>0){
          return "firefox";
         }else if(agent.indexOf("webkit")>0){
          return "webkit";
         }else if(agent.indexOf("gecko")>0 && agent.indexOf("rv:11")>0){
          return "ie11";
         }else{
          return "Others";
         }
        }
      
    /** 
     * http post请求方式 
     * @param urlStr 
     * @param params 
     * 
    **/  
    public static String post(String urlStr,Map<String,String> params){  
         URL connect;  
         StringBuffer data = new StringBuffer();    
         try {    
             connect = new URL(urlStr);    
             HttpURLConnection connection = (HttpURLConnection)connect.openConnection();    
             connection.setRequestMethod("POST");    
             connection.setDoOutput(true);   
             connection.setDoInput(true);  
             //connection.setRequestProperty("accept", "*/*");  
             //connection.setRequestProperty("connection", "Keep-Alive"); 
             connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");  //**很重要,指定编码集
//             connection.setRequestProperty("Content-Type","text/html;charset=UTF-8");
             //connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
           //conn.setRequestProperty("Cookie", cookiesAll.toString()); 设置cookie  若需要登录操作  
             OutputStreamWriter paramout = new OutputStreamWriter(    
                     connection.getOutputStream(),"utf-8");   
            String paramsStr = "";  
            for(String param : params.keySet()){  
                paramsStr += "&" + param + "=" + params.get(param);  
            }  
            System.out.println(paramsStr);
            if(!paramsStr.isEmpty()){  
                paramsStr = paramsStr.substring(1);  
            }  
            paramsStr="tablename=T_YW_AJ_SXCS&index=id&rows=[{%22addrcode%22:null,%22addrdesc%22:%22%E5%B9%BF%E4%B8%9C%E7%9C%81%E6%B7%B1%E5%9C%B3%E5%B8%82%E7%A6%8F%E7%94%B0%E5%8C%BA%E9%A6%99%E8%9C%9C%E6%B9%96%E8%A1%97%E9%81%93%E7%AB%B9%E5%9B%AD%E7%A4%BE%E5%8C%BA%E5%BB%BA%E4%B8%9A1%E6%A0%8B%E3%80%812%E6%A0%8B%E5%8D%95%E8%BA%AB%E5%85%AC%E5%AF%9325%22,%22address%22:%221%E5%9D%8A25-2%22,%22approved_type%22:null,%22area%22:%22%E6%B2%99%E5%98%B4%E7%A4%BE%E5%8C%BA%22,%22audit_time%22:null,%22audit_user%22:null,%22business_area%22:%22100%E3%8E%A1%E4%BB%A5%E4%B8%8B%22,%22business_card_no%22:%22%E6%97%A0%22,%22business_type%22:%22%E6%97%A7%E8%B4%A7%E4%B9%B0%E5%8D%96%22,%22bzdz%22:%22%E5%B9%BF%E4%B8%9C%E7%9C%81%E6%B7%B1%E5%9C%B3%E5%B8%82%E7%A6%8F%E7%94%B0%E5%8C%BA%E9%A6%99%E8%9C%9C%E6%B9%96%E8%A1%97%E9%81%93%E7%AB%B9%E5%9B%AD%E7%A4%BE%E5%8C%BA%E5%BB%BA%E4%B8%9A1%E6%A0%8B%E3%80%812%E6%A0%8B%E5%8D%95%E8%BA%AB%E5%85%AC%E5%AF%9325%22,%22checkstate%22:%220%22,%22cjsj%22:%222017-03-06%2015:46:34%22,%22code%22:null,%22createtime%22:%222018-03-29%2010:41:18%22,%22creator%22:null,%22creatorid%22:null,%22dl%22:null,%22dldm%22:null,%22doublecheck_time%22:null,%22dywgcode%22:null,%22fw%22:%2225%22,%22fwdm%22:%224403040070080500041000025%22,%22grid%22:%22440304005005000%22,%22grid_name%22:null,%22gxsj%22:null,%22id%22:%224A0AE7E0E782BD8EE0530142BE0ABB93%22,%22is_business_card%22:%22%E5%90%A6%22,%22is_up%22:%222%22,%22isadd%22:null,%22ischange%22:null,%22ischeck%22:%220%22,%22isdelete%22:0,%22isdoublecheck%22:null,%22istrouble%22:null,%22last_check_time%22:null,%22lat%22:null,%22ld%22:%221%E6%A0%8B%E3%80%812%E6%A0%8B%E5%8D%95%E8%BA%AB%E5%85%AC%E5%AF%93%22,%22lddm%22:%224403040070080500041%22,%22logouter%22:null,%22logouterid%22:null,%22logouttime%22:null,%22lon%22:null,%22name%22:%22%E6%97%A0%E5%90%8D%E9%BA%BB%E5%B0%86%E5%BA%97%22,%22operator_card_id%22:null,%22operator_name%22:%22%E9%AB%98%E9%87%91%E5%87%A4%22,%22operator_tel%22:%2283440400%22,%22owner_card_id%22:null,%22owner_name%22:null,%22owner_tel%22:null,%22photo%22:null,%22place_type%22:%2260021%22,%22qu%22:null,%22qudm%22:null,%22remark%22:null,%22sheng%22:null,%22shengdm%22:null,%22shi%22:null,%22shidm%22:null,%22sjly%22:null,%22sjlyfs%22:null,%22sq%22:%22%E6%B2%99%E5%98%B4%E7%A4%BE%E5%8C%BA%22,%22sqdm%22:%22440304004004%22,%22sqid%22:%22440304004004%22,%22status%22:%220%22,%22street%22:%22%E6%B2%99%E5%A4%B4%E8%A1%97%E9%81%93%22,%22streetid%22:%22440304004%22,%22times%22:null,%22update_id%22:null,%22update_name%22:null,%22update_time%22:null,%22xq%22:%22%E5%BB%BA%E4%B8%9A%22,%22xqdm%22:null,%22zx_audit_time%22:null,%22zx_audit_user%22:null}]";
             paramout.write(paramsStr);    
             paramout.flush();    
             BufferedReader reader = new BufferedReader(new InputStreamReader(    
                     connection.getInputStream(), "UTF-8"));    
             String line;                
             while ((line = reader.readLine()) != null) {            
                 data.append(line);              
             }    
             
             paramout.close();    
             reader.close();    
         } catch (Exception e) {    
             e.printStackTrace();
         }    
        return data.toString();  
    }  
    
    
    
    /** 
     * http post请求方式 
     * @param urlStr 
     * @param params 
     * 
    **/  
    public static String post(String urlStr,Map<String,String> params,JSONObject obj){  
         URL connect;  
         StringBuffer data = new StringBuffer();    
         try {    
             connect = new URL(urlStr);    
             HttpURLConnection connection = (HttpURLConnection)connect.openConnection();    
             connection.setRequestMethod("POST");    
             connection.setDoOutput(true);   
             connection.setDoInput(true);  
             connection.setRequestProperty("accept", "*/*");  
             connection.setRequestProperty("connection", "Keep-Alive");  
             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 
           
           //conn.setRequestProperty("Cookie", cookiesAll.toString()); 设置cookie  若需要登录操作  
             OutputStreamWriter paramout = new OutputStreamWriter(    
                     connection.getOutputStream(),"UTF-8");   
            String paramsStr = "";  
            for(String param : params.keySet()){  
                paramsStr += "&" + param + "=" + params.get(param);  
            }  
            if(!paramsStr.isEmpty()){  
                paramsStr = paramsStr.substring(1);  
            }  
             paramout.write(paramsStr);    
             paramout.flush();    
             BufferedReader reader = new BufferedReader(new InputStreamReader(    
                     connection.getInputStream(), "UTF-8"));    
             String line;                
             while ((line = reader.readLine()) != null) {            
                 data.append(line);              
             }    
             
             paramout.close();    
             reader.close();    
         } catch (Exception e) {    
             e.printStackTrace();
             obj.put("status", "2");
             String mes=e.getMessage();
             if(mes.indexOf("Connection timed out: connect")!=-1){
              obj.put("fReason", "连接超时");
           }
             return data.toString();  
         }
         obj.put("status", "1");
         
        return data.toString();  
    }
    
    public static String sendGet(String url, String param,JSONObject obj) {
      StringBuilder sb=new StringBuilder();
        //String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            //System.out.println("发送get请求********************"+urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            
            connection.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
            connection.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
            
            
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            //建立长连接
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                log.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
           log.error("发送GET请求出现异常!" + e);
            e.printStackTrace();
            obj.put("status", "2");
            String mes=e.getMessage();
            if(mes.indexOf("Connection timed out: connect")!=-1){
              obj.put("fReason", "连接超时");
           }
            return sb.toString();
        }
        //使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        obj.put("status", "1");
        return sb.toString();
    }

    
    /** 
     * 获取当前网络ip 
     * @param request 
     * @return 
     */  
    public static String getIpAddr(HttpServletRequest request){  
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    }
    
    //wfs.dps授权测试方法
    public static void testPost() throws IOException{
       Map<String,String> params = new HashMap<String,String>();
       /*
       //wfs授权配置 
       params.put("orderid", "");
       params.put("agencyrplinkage", "http://192.168.100.41:80/geostar/NoDelete/");
       params.put("metadataid", "8e4baaad-7300-4bc8-8e65-1e27fe27c20b");
       params.put("restitle", "NoDelete");
       params.put("restype", "service");
       params.put("orderType", "2");
       params.put("authorizationId", "863d9e9c-63f2-47c7-9ea4-750c4bb93fa5");
       params.put("authorizationName", "智慧城市");
       
       JSONObject interfacename = new JSONObject();
       interfacename.put("WFST", "GetCapabilities,DescribeFeatureType,GetFeature,Transaction,LockFeature");
       params.put("interfacename", interfacename.toJSONString());
       
       JSONObject layers = new JSONObject();
       layers.put("WFST", "V_YS_RK_CZRK,T_YS_W_BASE,V_YS_ZZ_BASE");
       params.put("layers", layers.toJSONString());
       
       params.put("layersId", "");
       params.put("maxVisitTimes", "0");
       
       JSONArray authorizerArr = new JSONArray();
       JSONObject authorizerArr1 = new JSONObject();
       authorizerArr1.put("authorizerName", "ajuser");
       authorizerArr1.put("authorizerId", "6ff8e3d1-b511-4a98-b1e4-3cae1d01ec34");
       authorizerArr.add(authorizerArr1);
       params.put("authorizerArr", authorizerArr.toJSONString());
       
       params.put("startdate", "2018-02-27");
       params.put("enddate", "2018-05-27");
       params.put("startip", "192.168.40.1,192.168.40.121");
       params.put("endip", "192.168.40.100,192.168.40.121");
       params.put("rangeFileId", "");
       
       JSONArray propertyArr = new JSONArray();
       JSONObject propertyArr1 = new JSONObject();
       propertyArr1.put("propertyName", "JDCODE");
       propertyArr1.put("relation", "2");
       propertyArr1.put("propertyVal", "440304010");
       propertyArr1.put("orderId", "");
       propertyArr1.put("layer", "V_YS_RK_CZRK");
       propertyArr1.put("logic", "0");
       propertyArr.add(propertyArr1);
       JSONObject propertyArr2 = new JSONObject();
       propertyArr2.put("propertyName", "DYWGCODE");
       propertyArr2.put("relation", "3");
       propertyArr2.put("propertyVal", "440304001010");
       propertyArr2.put("orderId", "");
       propertyArr2.put("layer", "V_YS_RK_CZRK");
       propertyArr2.put("logic", "0");
       propertyArr.add(propertyArr2);
       params.put("propertyArr", propertyArr.toJSONString());
       
       params.put("dpsDataSetArr", "[]");
       params.put("dpsPropertyArr", "[]");
       params.put("authorizeModel", "1");
       params.put("username","admin");*/
       
       //dps授权配置 
//     params.put("orderid", "");//订单id
//     params.put("agencyrplinkage", "http://192.168.100.41:80/geostar/NoDelete_DPS1/");//wfs请求地址,参数为代理地址
//     params.put("metadataid", "fd75fa56-2580-4e2b-94c5-b5200c11b312");//wfs服务在服务中心中的ID
//     params.put("restitle", "NoDelete_DPS1");//服务名称
//     params.put("restype", "service");//固定
//     params.put("orderType", "2");//固定
//     params.put("authorizationId", "863d9e9c-63f2-47c7-9ea4-750c4bb93fa5");//授权部门id
//     params.put("authorizationName", "智慧城市");//授权部门名称
//     
//     JSONObject interfacename = new JSONObject();
//     interfacename.put("DPS", "GetCapabilities,GetCatalog,GetDataSetList,DescribeDataSet,Query,Analysis");//授权接口
//     params.put("interfacename", interfacename.toJSONString());
//     
//     JSONObject layers = new JSONObject();
//     layers.put("DPS", "");//留空
//     params.put("layers", layers.toJSONString());//授权图层
//     
//     params.put("layersId", "");//留空
//     params.put("maxVisitTimes", "0");//最大访问次数
//     
//     JSONArray authorizerArr = new JSONArray();
//     JSONObject authorizerArr1 = new JSONObject();
//     authorizerArr1.put("authorizerName", "ajuser");
//     authorizerArr1.put("authorizerId", "6ff8e3d1-b511-4a98-b1e4-3cae1d01ec34");
//     authorizerArr.add(authorizerArr1);
//     params.put("authorizerArr", authorizerArr.toJSONString());//授权用户id和用户名
//     
//     params.put("startdate", "2018-02-27");//访问限制开始时间
//     params.put("enddate", "2018-05-27");//访问限制结束时间
//     params.put("startip", "192.168.40.1,192.168.40.121");//部门IP
//     params.put("endip", "192.168.40.100,192.168.40.121");
//     params.put("rangeFileId", "");//留空

//     params.put("propertyArr", "[]");//logic:条件关系 0为and,1为or  relation  关系运算 0:小于 1:小于等于 2:等于 3:模糊等于 4:大于 5:大于等于 6:不等于
       
//     params.put("dpsDataSetArr", "[]");//propertyShow:该数据集允许访问的字段,不限制为""
       params.put("rows", "[{\"address\":\"jrjfhfhfn\",\"bjtime\":null,\"community\":null,\"community_id\":null,\"creater_dept\":\"城管科\",\"creater_deptid\":\"44030400232\",\"creater_id\":\"wangjing1\",\"creater_name\":\"王晶\",\"ctime\":\"2017-06-07 16:24:45\",\"dbtime\":null,\"event_code\":\"440304002201706070001\",\"event_content\":\"xndndn\",\"event_keyword\":null,\"event_lv\":\"01\",\"event_name\":\"深城管2017字第146140号440304002201706070001\",\"event_source\":\"90\",\"event_time\":\"2017-07-11 00:22:00\",\"event_type\":null,\"event_typeid\":null,\"fbtime\":null,\"flowkey\":null,\"flowstate\":null,\"flowstateid\":null,\"gd_event_type\":null,\"gd_event_typeid\":null,\"gdtime\":null,\"gq_remark\":null,\"gq_type\":null,\"gqtime\":null,\"grid_code\":null,\"grid_name\":null,\"isdelete\":\"1\",\"pjtime\":null,\"point_x\":null,\"point_y\":null,\"pstime\":null,\"remark\":null,\"report_address\":null,\"report_code\":\"hnfndndjcj\",\"report_code_type\":\"sfz\",\"report_name\":\"bdbfncn\",\"report_phone\":null,\"source_blsx\":null,\"source_dept\":null,\"source_deptid\":null,\"source_id\":null,\"state\":\"-1\",\"street\":null,\"street_id\":null,\"systemid\":\"d811878b964f49e688f6765db3cfcc5d\",\"templateid\":null,\"time_limit\":8,\"time_sl\":60,\"utime\":\"2017-06-07 16:24:45\",\"geometry_type\":\"POINT\"}]");
       
       params.put("index", "systemid");//1是按用户,0是按部门,如果部门用户都授权还是1
       params.put("tablename","T_FB_EVENT_INFO");//当前登录用户
       
       //打印参数
  /*   Set set = params.entrySet();
       for(Iterator iter = set.iterator();iter.hasNext();){
            Map.Entry entry =  (Map.Entry)iter.next();
            System.out.println(entry.getKey()+":"+entry.getValue());
       }
       String paramsStr = "";  
        for(String param : params.keySet()){  
            paramsStr += "&" + param + "=" + URLEncoder.encode(params.get(param),"UTF-8");  
        } */
       String r = post("http://localhost:8080/Portal/api/wfsApplicationData/insertYwData", params);
       System.out.println(r);
    }
    
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param,String contentType) {
       OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection  conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
            conn.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
            
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
           if(contentType!=null && (!"".equals(contentType))){
              conn.setRequestProperty("Content-Type", contentType);
           }
            
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(),"utf-8");

            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
                InputStream inputStream = conn.getInputStream();
                 // 定义BufferedReader输入流来读取URL的响应
                 in = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                 String line;
                 while ((line = in.readLine()) != null) {
                     result += line;
                 }
            }else{
               InputStream errorStream = conn.getErrorStream();
               // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(errorStream,"utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                log.error("响应失败:"+conn.getResponseCode()+",响应信息"+conn.getResponseMessage()+",返回信息:"+result);
            }
           
        }catch (Exception e) {
            log.error("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
               log.error("关闭流异常"+ex);
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
       testPost();
    }
    
}

 使用如上工具类

可以将请求和参数传入,只需要合作单位提供接口url以及参数,即可远程访问

举例如下

    @Override
    @SystemLog(descrption = "远程调用接口获取详细信息", type = "查询", systemCode = Constants.SYSTEM_MODELCODE_COLLECT, modelName = "块地图定位")
    @GetMapping("/getDtdw")
    @ApiOperation(value = "远程调用接口获取详细信息 wangli", notes = "远程调用接口获取详细信息", response = StandardResult.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "accessToken", value = "令牌", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "ztdz", value = "主体地址", required = true, dataType = "String")
    })
    public StandardResult getDtdw(@RequestParam String ztdz) {
        try {
//            todo :远程调用接口获取详细信息
            int time = (int) (System.currentTimeMillis() / 1000);
            Map<String, Object> map = new HashMap<>();
            String url = "http://IP:端口/路径?user=nsltt&time=" + time + "&secret=" + MD5Utils.md5(time + "xxxx");
            String data = HttpClientUtils.sendGet(url);
            logger.info("data==========4" + data);
            JSONObject obj = JSON.parseObject(data);
            Object data1 = obj.get("data");
            String tokenData = JSON.toJSONString(data1);
            JSONObject jsonObject = JSON.parseObject(tokenData);
            String token = (String) jsonObject.get("token");
            String str= URLEncoder.encode(ztdz,"UTF-8");
            String attrUrl = "http://IP:端口/路径?token=" + token + "&addr=" + str + "&page=1&limit=2&fuzzy=true";
            String attrData = HttpClientUtils.sendGet(attrUrl);
            JSONObject attrJsonObject = JSON.parseObject(attrData);
            if (attrJsonObject != null) {
                Object attrData1 = attrJsonObject.get("data");
                String AttrJsonString = JSON.toJSONString(attrData1);
                JSONObject attrJsonObject1 = JSON.parseObject(AttrJsonString);
                JSONArray jsonArray = attrJsonObject1.getJSONArray("addrList");
                ArrayList<YwkTydzDzbqModel> ywkTydzDzbqModels = new ArrayList<>();
                logger.info("jsonArray==========4" + jsonArray);
                if (jsonArray != null && jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObj = jsonArray.getJSONObject(i);
                        YwkTydzDzbqModel ywkTydzDzbqModel = creatList(jsonObj);
                        ywkTydzDzbqModels.add(ywkTydzDzbqModel);
                    }
                }
                return StandardResult.ok(ywkTydzDzbqModels);
            }else {
                return StandardResult.ok();
            }
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
4.1 SNGraph 一 点、向量 基本运算 二 直线(线段、射线) 直线(线段、射线)用起点、方向(单位向量)、线段长度表示。 包括如下功能:  点是否在直线上。  假定点在直线上,点到直线起点的有向距离。如果点在直线上,点到直线距离为n。如果n>=0,则点在射线上;如果(n>=0)&&(n <= 线段长度) ,则点在线段上。  两直线是否平行或重合。  两直线是否重合。  两直线是否垂直。  两直线交点。  两非平行直线距离。  求垂足。 三 平面 通过过平面一点和方向(单位矢量)表示平面。包括如下功能:  点到平面的有向距离。通过平面标准法向量和距离,可以求垂足;通过点到平面的距离的正负,可以看出多个点是否在同侧;如果点到平面的距离为0,则点在平面上,否则不在平面上。  直线是否在平面上  平面和直线的交点 通过调用其他功能可以实现的功能:  平面的法向量平行于直线,则平面和直线垂直  平面的法向量垂直于直线,则平面和直线平行  平面的法向量平行(垂直)则平面平行(垂直)  平行平面的距离等于平面任意一点到另一平面的距离 四 矩阵 包括以下功能:  初始化为单位矩阵。  为向x,y,z方向缩放建立矩阵。  为任意方向缩放建立矩阵。投影平面,可以通过向平面法线方向缩放0实现。平面镜像,可以通过向平面法线方向缩放-1实现。  为对一个点镜像建立矩阵。  为对一条直线镜像建立矩阵。  为对一条对称轴旋转建立矩阵。  求对应行列式的值。  求逆矩阵。  求转置矩阵。  左乘。  求对应行列式的代数余子式。  常见运算符。 4.2 SN 封装了许多基础的功能。 一 接口  读写锁。 二 避免依赖其它类库 有些类经常用于库间接口,所以需要避免依赖其它类库。  字符串类、函数,比如:宽字符、多字符间的转换。  时间类。  数组的封装。 三 其它  将错误信息记录到全局变量中,应用场景:构造函数和析构函数中throw会引起不可预料的问题。  安全缓存,额外开辟若干个字节的空间,并初始化为一个特定值,如果不越界,这些值不会改变。  智能指针,为了将关联降为依赖。CAutoPtr<C> m_pC代替C m_c,头文件中不需要引用C类的头文件。只需要声明C类,在源文件中引用C类的头文件。  MD5。  RSA。  SHA。  考虑溢出的加减法。比如:int型的10亿加20亿,-10亿减20亿。  通过表名、列名、某些列的值生成sql语句。  安全指针和防野指针类。防野指针类:在构造函数中将状态初始为已初始化,在析构函数中将状态设置为已释放。安全指针在使用时之前判断 防野指针类释放是“已初始化”,否则抛出异常。  将有参数的函数统一成没参数返回值类型void的仿函数。  遍历文件夹的文件和子文件夹。  随机数和排列组合。  系列化和反系列化。将对象和变量转化成二进制,并将二进制转回变量和对象。  拆分,如字符串。 4.3 SNMFC 一 网络功能  网络基本功能:如获取本机IP,通过域名获取IP,IE版本。  HTML对话框的封装类。  用于服务端的,带“回调类”的绑定监听类,利用IO完成端口。  用于客户端的,带“回调类”连接类,利用select模式完成,可以指定是否开启新线程。连接时,可以指定超时时间,默认5秒。如果直接调用系统的connect,超时时间是75秒。  能够自动处理“粘包”、“拆包”的二进制解析类。  安全套接字的辅助类,如:设置发送、连接超时。  比较服务端的某个文件夹和客户端的某个文件夹,并更新那些md5不同的文件。 二 多线程  用临界区实现的线程锁,和线程读写锁。  窗口辅助类。  开启一个线程并调用一个函数。  开启一个线程并循环调用一个函数。  支持多线程的日志。  启动一个线程,等待若干秒后,Post或Send一个消息后,结束线程。 三 界面  三态树控件。  列表框扩展类和函数。  树控件的扩展。  组合框的扩展。  关于窗口功能的封装。比如:从左到右依次排列子窗口,排不下则下一行。可以指定行间距。页眉和页脚是行间距的一半。  位图的加载和显示。 四 其它  Ini文件。  数组封装类。  获取硬件信息,如网卡。  文件或文件夹的常用功能。  注册表的扩展。 4.4 SNSTL  数组(向量)扩展。  用于多线程的向量。  JSON解析。  集合的扩展。  映射的扩展。  指针向量,可以存派生类。  指针映射,可以存派生类。 4.5 其它库  UnitTest,本机单元测试项目,对整个库的重要功能进行单元测试。  SNBCG,著名界面库的扩展,几乎没使用。  SNPicture,图形图像的处理(如转换bmp格式),几乎没使用。  SNMath,数学及数据结构库,几乎没使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨会停rain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值