-
Annotation: @CrossOrigin
-
Gateway Integration
-
Httpclient
Why is there a cross-domain problem
Because of the browser's same-origin policy, cross-domains are created. For example, an asynchronous request is sent to two different sources, such as two different ports or two different protocols or different domains. Because of the browser's security considerations, a homology policy is created, and interaction is not allowed if it does not come from the same place.
Common cross-domain solutions
(1) Routing
Routing is the most basic part of the gateway. The routing information consists of an ID, a destination URL, a set of assertions and a set of Filters. If the assertion route is true, it means that the requested URL and the configuration match
(2) Assertion
The Spring Cloud Gateway assertion function input type is ServerWebExchange in the Spring 5.0 framework. the Spring Cloud Gateway assertion function allows the developer to define a match to any information from the http request, such as request headers, parameters, etc.
(3) Filters
There are two types of filters in Spring cloud gateway, Gateway Filter and Global Filter. filter Filter will modify the request and response processing
The Spring cloud Gateway sends the request. The Gateway Handler Mapping then finds a route that matches the request and sends it to the Gateway web handler, which then sends the request through the specified filter chain to the actual service to execute the business logic and then returns it.
The project uses
Create a new module service_gateway
<dependencies>
<!-- Public Module Dependencies -->
<dependency>
<groupId>com.lzq</groupId>
<artifactId>service_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Service Registration -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
Configuration file
# Service Port
server.port=9090
# Service Name
spring.application.name=service-gateway
# nacos service address default 8848
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8888
# Discovering routes using services
spring.cloud.gateway.discovery.locator.enabled=true
#Set the route id
spring.cloud.gateway.routes[0].id=service-hosp
#Set the uri lb load balancing of the route
spring.cloud.gateway.routes[0].uri=lb://service-hosp
#Set route assertion, proxy servicerId to auth-service's /auth/ path
spring.cloud.gateway.routes[0].predicates= Path=/*/hosp/**
#Set the route id
spring.cloud.gateway.routes[1].id=service-cmn
#Set the uri of the route
spring.cloud.gateway.routes[1].uri=lb://service-cmn
#Set route assertion, proxy servicerId to auth-service's /auth/ path
spring.cloud.gateway.routes[1].predicates= Path=/*/cmn/**
#Set the route id
spring.cloud.gateway.routes[2].id=service-hosp
#Set the uri of the route
spring.cloud.gateway.routes[2].uri=lb://service-hosp
#Set route assertion, proxy servicerId to auth-service's /auth/ path
spring.cloud.gateway.routes[2].predicates= Path=/*/userlogin/**
Create startup class
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
Modify the front-end.evn file to change the access gateway port number
When doing cluster deployment, he will implement load balancing according to the name
Cross-domain understanding: after sending a request, the gateway filter will intercept the request, release the cross-domain and forward it to the server
Cross-domain configuration classes
public class CorsConfig {
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
If you use annotated cross-domain before, you need to remove @CrossOrigin
Httpclient
Common usage scenarios: interaction between interfaces between multiple systems, crawlers
http native request, get Baidu home page code
public class HttpTest {
@Test
public void test1() throws Exception {
String url = "https://www.badu.com";
URL url1 = new URL(url);
//url link
URLConnection urlConnection = url1.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
//Get the httpURLConnection input stream
InputStream is = httpURLConnection.getInputStream();
//Convert to string
InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(reader);
String line;
//Read out the string line by line
while ((line = br.readLine())!= null){
System.out.println(line);
}
}
}
//Set the request type
httpURLConnection.setRequestMethod("GET");
//Request contains request line, space, request header, request body
//Set the request header code
httpURLConnection.setRequestProperty("Accept-Charset","utf-8");
Use HttpClient to send requests, receive responses
Create an HttpClient object.
If you need to send a GET request, create an HttpGet object; if you need to send a POST request, create an HttpPost object.
If you need to send request parameters, you can call the HttpGet, HttpPost common setParams (HetpParams params) method to add request parameters; for the HttpPost object, you can also call the setEntity (HttpEntity entity) method to set the request parameters.
Call the HttpClient object execute(HttpUriRequest request) to send the request, the method returns an HttpResponse.
Call HttpResponse getAllHeaders(), getHeaders(String name) and other methods to obtain the server's response headers; call HttpResponse getEntity() method to obtain the HttpEntity object, the object wraps the server's response content. The program can get the response content of the server through this object.
Release the connection. Whether the execution of the method is successful or not, the connection must be released
Integration testing, adding dependencies
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
@Test
public void test2(){
//Closeable httpclient client, equivalent to opening a browser
CloseableHttpClient client = HttpClients.createDefault();
String url = "https://www.baidu.com";
//Constructing the httpGet request object
HttpGet httpGet = new HttpGet(url);
//Response
CloseableHttpResponse response = null;
try {
response = client.execute(httpGet);
// Get Content
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}finally {
//Close the stream
if (client != null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Used in the project, the system calls the platform interface to save information, according to the incoming josn data to save information
in the system
public String saveHospital(String data, HttpServletRequest request) {
try {
apiService.saveHospital(data);
} catch (YyghException e) {
return this.failurePage(e.getMessage(),request);
} catch (Exception e) {
return this.failurePage("Data Anomalies",request);
}
return this.successPage(null,request);
}
saveHospital method
public boolean saveHospital(String data) {
JSONObject jsonObject = JSONObject.parseObject(data);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("hoscode","10000");
paramMap.put("hosname",jsonObject.getString("hosname"))
//Pictures
paramMap.put("logoData", jsonObject.getString("logoData"));
// http://localhost:8201/api/hosp/saveHospital
//httpclient
JSONObject respone =
HttpRequestHelper.sendRequest(paramMap,this.getApiUrl()+"/api/hosp/saveHospital");
System.out.println(respone.toJSONString());
if(null != respone && 200 == respone.getIntValue("code")) {
return true;
} else {
throw new YyghException(respone.getString("message"), 201);
}
}
HttpRequestHelper tool class
/**
* Encapsulating synchronization requests
* @param paramMap
* @param url
* @return
*/
public static JSONObject sendRequest(Map<String, Object> paramMap, String url){
String result = "";
try {
//Encapsulating post parameters
StringBuilder postdata = new StringBuilder();
for (Map.Entry<String, Object> param : paramMap.entrySet()) {
postdata.append(param.getKey()).append("=")
.append(param.getValue()).append("&");
}
log.info(String.format("--> Send request: post data %1s", postdata));
byte[] reqData = postdata.toString().getBytes("utf-8");
byte[] respdata = HttpUtil.doPost(url,reqData);
result = new String(respdata);
log.info(String.format("--> Response results: result data %1s", result));
} catch (Exception ex) {
ex.printStackTrace();
}
return JSONObject.parseObject(result);
}
HttpUtil tool class
public static byte[] send(String strUrl, String reqmethod, byte[] reqData) {
try {
URL url = new URL(strUrl);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.setDoOutput(true);
httpcon.setDoInput(true);
httpcon.setUseCaches(false);
httpcon.setInstanceFollowRedirects(true);
httpcon.setConnectTimeout(CONN_TIMEOUT);
httpcon.setReadTimeout(READ_TIMEOUT);
httpcon.setRequestMethod(reqmethod);
httpcon.connect();
if (reqmethod.equalsIgnoreCase(POST)) {
OutputStream os = httpcon.getOutputStream();
os.write(reqData);
os.flush();
os.close();
}
BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"utf-8"));
String inputLine;
StringBuilder bankXmlBuffer = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
bankXmlBuffer.append(inputLine);
}
in.close();
httpcon.disconnect();
return bankXmlBuffer.toString().getBytes();
} catch (Exception ex) {
log.error(ex.toString(), ex);
return null;
}
}
Corresponding platform interface
public class ApiController {
private HospitalService hospitalService;
public R saveHospital(HttpServletRequest request) {
//Fetch the value passed from the front-end interface via request
Map<String, String[]> parameterMap = request.getParameterMap();
//Convert an array value to a value
Map<String, Object> paramMap = HttpRequestHelper.switchMap(parameterMap);
//Converting a map collection to a josn string
String mapStr = JSONObject.toJSONString(paramMap);
//josn string to object
Hospital hospital = JSONObject.parseObject(mapStr, Hospital.class);
//Join in MongoDB
hospitalService.saveHosp(hospital);
return R.ok();
}
}
Ready to call each other in different systems