Because of the project requirements, communication between the two systems is required. After some research, it was decided to use http request.
There is nothing to say about the server. It is originally used to access it using web pages. Therefore, after spring boot is started, the controller layer interface is automatically exposed. The client can just call the corresponding url, so here is mainly the client.
First, I customized a tool class DeviceFactoryHttp for processing http requests. Since it is URL access, there are two problems that need to be handled, one is the URL that requests the service and the parameters of the request server. The message header of the client requests the service url: Request the server url I define is the same URL parameters as the client: There are two types of parameters on the server that are encapsulated, similar to the following:
http://localhost:8080/switch/getAllStatus?data{"interface name":"getAllStudentStaus"}
One is not encapsulated, similar to the following:
http://localhost:8080/switch/getStudentInfoByName?name=zhangSan
First, it is encapsulated:
1: Initialize httpclient
private static HttpClient client = null; static { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(128);cm.setDefaultMaxPerRoute(128);client = HttpClients.custom().setConnectionManager(cm).build(); }Two: Get the requested url, because the url defined by my server is the same as the client, so I directly use the requested client's url
//Get the requested urlpublic StringBuffer getUrlToRequest(HttpServletRequest request) { StringBuffer url=request.getRequestURL();//Get the requested url(http://localhost:8080/switch/getStudentInfoByName) String[] splitArr=url.toString().split("/"); String appName=splitArr[3];//Project name String ipReport=splitArr[2];//Project ip:report String resultStr=url.toString().replaceAll(appName,DevFacConstans.facname).replaceAll(ipReport, DevFacConstans.ip+":"+DevFacConstans.report); return new StringBuffer(resultStr); }Get the url to split according to /, because I am testing environment, production environment ip, port number (domain name) is definitely not localhost, some will add the project name before it, so I will replace the value corresponding to split.
Three: assemble the request parameters and call the http request
/*** Send http request with request* Call the controller layer* @param request * @return */public String sendHttpToDevFac(HttpServletRequest request)throws Exception { HttpClient client = null; String returnResult=""; // http://localhost:8080/leo/1.0/h5/login StringBuffer urlBuffer=getUrlToRequest(request);//Call the second step, get url //Get parameters and assemble String dataAsJson = request.getParameter("data"); String encoderData=URLEncoder.encode(dataAsJson,"utf-8"); HttpGet get=new HttpGet(urlBuffer.append("?data=").append(encoderData).toString()); //set headersEnumeration<String> headerNames=request.getHeaderNames(); while(headerNames.hasMoreElements()) {String headerName=headerNames.nextElement(); String headerValue=request.getHeader(headerName); get.setHeader(headerName, headerValue); }client=DeviceFactoryHttp.client;logger.info("Start call http request, request url:"+urlBuffer.toString());HttpResponse rep=client.execute(get); returnResult=EntityUtils.toString(rep.getEntity(),"utf-8");logger.info("http request call ends!!");return returnResult; }First get the requested parameters, then assemble the parameters behind the url. Don't forget about URLEncoder.encode. This is because the parameters will have some symbols. You need to encode the parameters before adding the url. Otherwise, an exception will be thrown. Set headers: Because some information servers will take them out of the request header, I also set the client's request header to the server's request. The requested url and the requested parameters can be spliced and client.exceute(get) to execute the request.
The above is that my browser directly passes the request request request as a parameter to my client, so I can get the url directly from the request. Some do not have a request, so I need to get it from the context of the request.
Unpackaged:
First get the request's
/*** Get request* @return */public static HttpServletRequest getRequest(){ ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = ra.getRequest(); return request; }2: After having request, there is a url. Let’s parse the request parameters, because this parameter is not encapsulated, so all request parameters are obtained.
/** * There is no request request, call the controller layer * @param key * @param interfaceName * @param strings * @return * @throws Exception */ public String centerToDeviceFacNoRequest(String key,String interfaceName)throws Exception { try { HttpServletRequest request=getRequest();//The first step above is to get the url from the context //Get the reuquest request parameter Enumeration<String> names= request.getParameterNames(); Map<String,String>paramMap=new HashMap<>(); //Transtraight request map while(names.hasMoreElements()) { String name=names.nextElement(); String value=(String) request.getParameter(name); paramMap.put(name, value); } //Call the method to send http request return sendHttpToDevFacNoData(paramMap,request); } catch (Exception e) { e.printStackTrace(); } //end return null; } Three: Send http request
/** * Send http request, [without data] * @return */ public String sendHttpToDevFacNoData(Map<String,String>paramMap,HttpServletRequest request)throws Exception { HttpClient client = null; String result=""; StringBuffer dataBuffer=getUrlToRequest(request);//Get url dataBuffer.append("?"); client=DeviceFactoryHttp.client; Iterator<Entry<String, String>> paamIt=paramMap.entrySet().iterator(); while(paamIt.hasNext()) { Entry<String, String> entry=paamIt.next(); dataBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } String resultUrl=dataBuffer.toString().substring(0, dataBuffer.toString().lastIndexOf("&")); //Send request HttpGet get=new HttpGet(resultUrl); //set headers Enumeration<String> headerNames=request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName=headerNames.nextElement(); String headerValue=request.getHeader(headerName); get.setHeader(headerName, headerValue); } HttpResponse rep=client.execute(get); logger.info("Start call http request, request url:"+resultUrl); //Return result=EntityUtils.toString(rep.getEntity(),"utf-8"); logger.info(" http request call ends!!"); return result; }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.