Home  >  Article  >  Java  >  How to solve java background calling interface and handle cross-domain issues

How to solve java background calling interface and handle cross-domain issues

WBOY
WBOYforward
2023-05-16 11:04:051227browse

java calling interface and handling cross-domain

When building a system, sometimes the js code of system A needs to call the interface of system B, which will cause cross-domain phenomena. Cross-domain processing can be handled through background calls. Domain

problem, this means a bit "agency".

Record a common method here

public String httpPost(String urlStr,Map<String,String> params){
    URL connect;
    StringBuffer data = new StringBuffer();  
    try {  
        connect = new URL(urlStr);  
        HttpURLConnection connection = (HttpURLConnection)connect.openConnection();  
        connection.setRequestMethod("POST");  
        connection.setDoOutput(true); 
        connection.setDoInput(true);
        connection.setUseCaches(false);//post不能使用缓存
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        OutputStreamWriter paramout = new OutputStreamWriter(  connection.getOutputStream(),"UTF-8"); 
        String paramsStr = "";   //拼接Post 请求的参数
        for(String param : params.keySet()){
           paramsStr += "&" + param + "=" + params.get(param);
        }  
        if(!paramsStr.isEmpty()){
            paramsStr = paramsStr.substring(1);
        }
        paramout.write(paramsStr);  
        paramout.flush();  
        BufferedReader reader = new BufferedReader(new InputStreamReader(  
                    connection.getInputStream(), "UTF-8"));  
        String line;              
        while ((line = reader.readLine()) != null) {          
            data.append(line);            
        }   
        paramout.close();  
            reader.close();  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
       return data.toString();
}

Cross-domain issues caused by calling external interfaces

Background: On our system, refer from the outside Developed a suggestion system. In the suggestion system, after a user is given a comment or reply, the number of unread messages is displayed in my messages.

Achieved effect: When the number of unread messages in the suggestion system is greater than 0, a red dot indicating that there are unread messages will appear at the location where our system introduces the suggestion system.

In the backend of the proposed system, we wrote a countBlog interface to obtain the number of unread messages (json format)

In the frontend of our system, we introduced the interface to pass the returned unread messages Read the number of messages to control the red dot display

Report cross-domain problem bug after running:

Solution

Method 1: Annotate @CrossOrigin

Method 2: addCorsMappings configuration

@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")  
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");  
    }

Disadvantage: After using this method to configure and then use a custom interceptor, the cross-domain related configuration will become invalid.

The reason is the order of the requests. When the request comes, it will enter the interceptor first instead of entering the mapping, so there is no configured cross-domain information in the returned header information. The browser will report a cross-domain exception.

Method 3: Use CorsFilter filter

private CorsConfiguration corsConfig() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    * 请求常用的三种配置,*代表允许所有,当时你也可以自定义属性(比如header只能带什么,只能是post方式等等)
    */
    corsConfiguration.addAllowedOrigin("*");
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setMaxAge(3600L);
    return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", corsConfig());
    return new CorsFilter(source);
}

The above is the detailed content of How to solve java background calling interface and handle cross-domain issues. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete