参考文献
两个java项目的服务端通信之HttpURLConnection方式:https://blog.csdn.net/cw_hello1/article/details/51455203
postman测试带session的接口:https://blog.csdn.net/maryshine/article/details/81014887
请求服务端
请求方法如下:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnection {
/**
* java项目的服务端之间的通信
* @param requestUrl 请求url
* @param jsessionId 浏览器的访问的Cookie,即被访问的服务端的session。若被访问的服务器没有做url过滤器,则该参数可以为null。
* @return
*/
public static String httpUrlConnecion(String requestUrl, String jsessionId){
try {
HttpURLConnection con = (HttpURLConnection) new URL(requestUrl).openConnection();
if(jsessionId != "" && jsessionId != null){
con.setRequestProperty("Cookie", "JSESSIONID="+jsessionId);
}
con.setRequestMethod("GET");
con.connect();
int responseCode = con.getResponseCode();
if(responseCode == con.HTTP_OK){
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while((line =reader.readLine()) != null){
sb.append(line);
}
reader.close();
con.disconnect();
return sb.toString();
}else{
return "error";
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "error";
}
}
调用方法如下:
/**
* 登录
* @return
* @throws IOException
*/
@RequestMapping("login")
public ModelAndView login(HttpServletRequest request,HttpServletResponse httpResp,
HttpSession session, SysUser sysUser, String jsessionId) throws IOException {
String loginUrl = "http://{请求服务器IP}:{PORT}/{请求服务器项目名}/user/login.do";
String requestUrl = "http://{被请求服务器IP}:{PORT}/{被请求服务器项目名}/user/checkLogin.do";
String params = "?loginId="+sysUser.getLoginid()+"&jsessionId="+jsessionId;
String result = HttpUrlConnection.httpUrlConnecion(requestUrl+params, jsessionId);
if(!"true".equals(result)){
return new ModelAndView("redirect:"+loginUrl);
}else{
……
}
}
被访问服务端
被请求的资源如下:
/**
* 各子系统调用,查看主系统该用户是否登录,判断login.do是否可以免密码登陆
* @param userId
* @return
*/
@RequestMapping("/checkLogin")
@ResponseBody
public String checkLogin(HttpServletRequest request, HttpSession session, String loginId, String jsessionId){
Map<String, HttpSession> sessionMap = CacheManager.getSessionMap();
if(false == sessionMap.containsKey(loginId)){
return "false";
}else{
if(jsessionId.equals(sessionMap.get(loginId).getId())){
return "true";
}else{
return "false";
}
}
}