新建一个amven项目 A

pom文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.songzixian</groupId>
  <artifactId>test-web-a</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
  </parent>
  <dependencies>
    <!-- SpringBoot 对lombok 支持 -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>

    <!-- SpringBoot web 核心组件 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <!-- SpringBoot 外部tomcat支持 -->
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>

    <!-- springboot-log4j -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j</artifactId>
      <version>1.3.8.RELEASE</version>
    </dependency>
    <!-- springboot-aop 技术 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>
  </dependencies>
</project>

新建application.yml文件

server:
  port: 8080
spring:
  mvc:
    view:
      prefix: /WEB-INF/
      suffix: .jsp

新建AIndexController

@Controller
@SpringBootApplication
public class AIndexController {

    @RequestMapping("/aIndexJsp")
    public String aIndexJsp() {
        return "aIndexJsp";
    }

    // 使用HttpClient进行方法B接口
    @RequestMapping("/forWardB")
    @ResponseBody
    public JSONObject forWardB() {
        JSONObject result = HttpClientUtils.httpGet("http://192.168.78.1:8081/getBInfo");
        return result;
    }

    public static void main(String[] args) {
        SpringApplication.run(AIndexController.class, args);
    }

}

新建HttpClientUtils工具类

    public class HttpClientUtils {
        // 日志记录
        private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    
        private static RequestConfig requestConfig = null;
    
        static {
            // 设置请求和传输超时时间
            requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        }
    
        /**
         * post请求传输json参数
         *
         * @param url
         *            url地址
         * @param jsonParam
         *            参数
         * @return
         */
        public static JSONObject httpPost(String url, JSONObject jsonParam) {
            // post请求返回结果
            CloseableHttpClient httpClient = HttpClients.createDefault();
            JSONObject jsonResult = null;
            HttpPost httpPost = new HttpPost(url);
            // 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            try {
                if (null != jsonParam) {
                    // 解决中文乱码问题
                    StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/json");
                    httpPost.setEntity(entity);
                }
                CloseableHttpResponse result = httpClient.execute(httpPost);
                // 请求发送成功,并得到响应
                if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String str = "";
                    try {
                        // 读取服务器返回过来的json字符串数据
                        str = EntityUtils.toString(result.getEntity(), "utf-8");
                        // 把json字符串转换成json对象
                        jsonResult = JSONObject.parseObject(str);
                    } catch (Exception e) {
                        logger.error("post请求提交失败:" + url, e);
                    }
                }
            } catch (IOException e) {
                logger.error("post请求提交失败:" + url, e);
            } finally {
                httpPost.releaseConnection();
            }
            return jsonResult;
        }
    
        /**
         * post请求传输String参数 例如:name=Jack&sex=1&type=2
         * Content-type:application/x-www-form-urlencoded
         *
         * @param url
         *            url地址
         * @param strParam
         *            参数
         * @return
         */
        public static JSONObject httpPost(String url, String strParam) {
            // post请求返回结果
            CloseableHttpClient httpClient = HttpClients.createDefault();
            JSONObject jsonResult = null;
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            try {
                if (null != strParam) {
                    // 解决中文乱码问题
                    StringEntity entity = new StringEntity(strParam, "utf-8");
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/x-www-form-urlencoded");
                    httpPost.setEntity(entity);
                }
                CloseableHttpResponse result = httpClient.execute(httpPost);
                // 请求发送成功,并得到响应
                if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String str = "";
                    try {
                        // 读取服务器返回过来的json字符串数据
                        str = EntityUtils.toString(result.getEntity(), "utf-8");
                        // 把json字符串转换成json对象
                        jsonResult = JSONObject.parseObject(str);
                    } catch (Exception e) {
                        logger.error("post请求提交失败:" + url, e);
                    }
                }
            } catch (IOException e) {
                logger.error("post请求提交失败:" + url, e);
            } finally {
                httpPost.releaseConnection();
            }
            return jsonResult;
        }
    
        /**
         * 发送get请求
         *
         * @param url
         *            路径
         * @return
         */
        public static JSONObject httpGet(String url) {
            // get请求返回结果
            JSONObject jsonResult = null;
            CloseableHttpClient client = HttpClients.createDefault();
            // 发送get请求
            HttpGet request = new HttpGet(url);
            request.setConfig(requestConfig);
            try {
                CloseableHttpResponse response = client.execute(request);
    
                // 请求发送成功,并得到响应
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 读取服务器返回过来的json字符串数据
                    HttpEntity entity = response.getEntity();
                    String strResult = EntityUtils.toString(entity, "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(strResult);
                } else {
                    logger.error("get请求提交失败:" + url);
                }
            } catch (IOException e) {
                logger.error("get请求提交失败:" + url, e);
            } finally {
                request.releaseConnection();
            }
            return jsonResult;
        }
    }

启动类

    /**
     * @author songzixian
     * @create 2019-09-08 上午 3:06
     * @description
     */
    @SpringBootApplication
    public class App1 {
    
        public static void main(String[] args) {
            SpringApplication.run(App1.class,args);
        }
    }

新建一个jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript"
            src="http://www.itmayiedu.com/static/common/jquery-1.7.2.min.js?t=2017-07-27"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
                type : "POST",
                async : false,
                url : "http://api.itmayiedu.com/b/getBInfo",
                dataType : "json",
                success : function(data) {
                    alert(data["retCode"]);
                },
                error : function() {
                    alert('fail');
                }
            });

        });
    </script>
</head>
<body>我是A项目,正在调用B项目
</body>
</html>

新建一个amven项目 B


pom文件
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.songzixian</groupId>
  <artifactId>test-web-b</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
  </parent>
  <dependencies>
    <!-- SpringBoot 对lombok 支持 -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>

    <!-- SpringBoot web 核心组件 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <!-- SpringBoot 外部tomcat支持 -->
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>

    <!-- springboot-log4j -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j</artifactId>
      <version>1.3.8.RELEASE</version>
    </dependency>
    <!-- springboot-aop 技术 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>
  </dependencies>
</project>

新建application.yml文件

server:
  port: 8081
spring:
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp

新建BIndexController

@RestController
@SpringBootApplication
public class BIndexController {

    // 该接口提供给A项目进行ajax调用
    @RequestMapping("/getBInfo")
    public Map<String, Object> getBInfo(HttpServletResponse response) {
        // 告诉客户端(浏览器 )允许跨域访问 *表示所有域名都是可以 在公司中正常的代码应该放入在过滤器中
        // response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("retCode", "200ok");
        result.put("retMsg", "数据请求成功");
        result.put("retMsg", "宋子宪博客");
        result.put("retMsg", "www.songzixian.com");
        return result;
    }

    // 使用jsonp 解决跨域问题
    // @RequestMapping("/getBInfo")
    // public void getBInfo(HttpServletResponse response, String jsonpCallback)
    // throws IOException {
    // // 告诉客户端(浏览器 )允许跨域访问 *表示所有域名都是可以 在公司中正常的代码应该放入在过滤器中
    // // Map<String, Object> result = new HashMap<String, Object>();
    // // result.put("retCode", "200");
    // // result.put("retMsg", "登陆成功");
    // JSONObject result = new JSONObject();
    // result.put("retCode", "200");
    // result.put("retMsg", "登陆成功");
    // PrintWriter writer = response.getWriter();
    // writer.println(jsonpCallback + "(" + result.toJSONString() + ")");
    // writer.close();
    // }

    public static void main(String[] args) {
        SpringApplication.run(BIndexController.class, args);
    }

}

访问

http://ip地址:8081/getBInfo

试例:http://192.168.78.1:8081/getBInfo
使用HttpClient解决网站跨域问题方案.png

Last modification:September 8, 2019
如果觉得这篇技术文章对你有用,请随意赞赏