1.背景
两个系统,一个认证系统,一个入学系统,入学系统要调用认证系统获得数据。
2.实现思路
入学系统web.xml中配置访问认证系统接口配置,将接口作为web的全局参数,示例:
<!-- 统一认证教师接口 -->
<context-param>
<param-name>teacherInterface</param-name>
<param-value>http://192.168.1.104/sso/global/dataInterface/getTeacher.action</param-value>
</context-param>
入学系统要调用接口的方法中,获取web上下文全局参数,并在方法中实现http请求,获得接口返回的参数,示例:
//sturts获取servletContext对象 ServletContext context = ServletActionContext.getServletContext(); //获取web.xml中全局参数 String teacherInterface = context.getInitParameter("teacherInterface"); //通过java.net.url和java.net.urlConnection模拟http的post请求 result = doPOST(teacherInterface,params);
使用POST方法读取HTTP中的数据
public static String doPOST(String urlAddress, String params) { try { // 创建URL对象 URL url = new URL(urlAddress); // 打开连接 获取连接对象 URLConnection connection = url.openConnection(); // 设置请求编码 connection.addRequestProperty("encoding", "GBK"); // 设置允许输入 connection.setDoInput(true); // 设置允许输出 connection.setDoOutput(true); // 从连接对象中获取输出字节流对象 OutputStream outputStream = connection.getOutputStream(); // 将输出的字节流对象包装成字符流写出对象 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); // 创建一个输出缓冲区对象,将要输出的字符流写出对象传入 BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); // 向输出缓冲区中写入请求参数 if(params != null){ bufferedWriter.write(params); } // 刷新输出缓冲区 bufferedWriter.flush(); // 从连接对象中获取输入字节流对象 InputStream inputStream = connection.getInputStream(); // 将输入字节流对象包装成输入字符流对象,并将字符编码为GBK格式 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK"); // 创建一个输入缓冲区对象,将要输入的字符流对象传入 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // 创建一个字符串对象,用来接收每次从输入缓冲区中读入的字符串 String line; // 创建一个可变字符串对象,用来装载缓冲区对象的最终数据,使用字符串追加的方式,将响应的所有数据都保存在该对象中 StringBuilder stringBuilder = new StringBuilder(); // 使用循环逐行读取缓冲区的数据,每次循环读入一行字符串数据赋值给line字符串变量,直到读取的行为空时标识内容读取结束循环 while ((line = bufferedReader.readLine()) != null) { // 将缓冲区读取到的数据追加到可变字符对象中 stringBuilder.append(line); } // 依次关闭打开的输入流 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); // 依次关闭打开的输出流 bufferedWriter.close(); outputStreamWriter.close(); outputStream.close(); // 将可变字符串转换成String对象返回 return stringBuilder.toString(); } catch (IOException e) { e.printStackTrace(); } return null; }
![](https://image.shishitao.com:8440/aHR0cHM6Ly9pbWcyMDIwLmNuYmxvZ3MuY29tL2Jsb2cvMzU2OTUvMjAyMTEwLzM1Njk1LTIwMjExMDA4MTYwNjI0ODEzLTE2OTQ1OTE1OTguanBn.jpg?w=700&webp=1)