通过httpclient来使用服务端发请求,避免前端发请求引起的跨域session丢失问题
/** * 测试连接服务 * * @return */ @RequestMapping("/test/connection") public ToClientViewModel<String> testConnectionService(){ ToClientViewModel<String> testResult = new ToClientViewModel<>(); testResult.setData("连接成功"); testResult.setStatus(200); testResult.setMsg(" "); return testResult; } @RequestMapping("/test/connectionTest") public @ResponseBody String connectionTest1(String ip, String port){ String url = "http://"+ip+":"+port+"/system/test/connection"; PrintWriter out = null; String result = ""; HttpURLConnection conn = null; InputStream is = null; BufferedReader br = null; StringBuffer strBuffer = new StringBuffer(); try { URL realUrl = new URL(url); // 打开和URL之间的连接 conn = (HttpURLConnection) realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestMethod("GET"); conn.setConnectTimeout(20000); conn.setReadTimeout(300000); // 传输数据为json,如果为其他格式可以进行修改 conn.setRequestProperty("Content-Type", "application/json"); is = conn.getInputStream(); br = new BufferedReader( new InputStreamReader(is)); String line = null; while ((line=br.readLine())!= null) { strBuffer.append(line); } result = strBuffer.toString(); } catch (Exception e) { System.out.println( "发送 GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (br != null) { br.close(); } if (conn != null) { conn.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }