最近有个需求是需要和其他厂商进行系统接口对接,我们平台属于前端展示系统,简称F系统,服务厂商属于接口服务提供方,简称B系统。
问题:F系统以Ajax的方式向B系统发送请求进行接口调用,F系统得到的响应码为403。在F系统所在服务器通过postman向B系统进行接口调用测试可以正确得到响应码为200的响应结果,由此可排除网络不通的假设。那基本可以判定是请求跨域问题。
解决方案:由于B系统不配合做代码改造,故,在F系统中新增HttpClient方式向B系统进行接口调用,然后再将B系统的响应结果反馈给F系统的前端调用层。
示例代码如下:
package com.tmh.hc;
import java.io.IOException;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HcServlet4Xxx extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
try {
String netIp = "10.45.32.9";
String netPort = "8687";
try {
ResourceBundle rb = ResourceBundle.getBundle("config");
String netflg = rb.getString("netflg");
if ("inner".equalsIgnoreCase(netflg)){
netIp = rb.getString("innernetip");
netPort = rb.getString("innernetport");
} else if("out".equalsIgnoreCase(netflg)){
netIp = rb.getString("outnetip");
netPort = rb.getString("outnetport");
}
} catch (Exception e) {
System.err.println("读取配置文件出错");
System.err.println(e);
}
// 创建默认连接
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpGet对象,处理get请求,转发到B站点
String url = "http://" + netIp + ":" + netPort + "/gateway/api/1/main/xx/getXxx";
String number = req.getParameter("number");
HttpGet httpGet = new HttpGet(url + "?number=" + number + "&token=xx");
httpGet.setHeader("key", "123456789");
// 执行
CloseableHttpResponse response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
// 获取状态
System.out.println("HcServlet4Xxx 请求结果为:" + code);
if (code == 200) {
// 获取B站点返回的结果
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
// 把结果返回给F站点
resp.getWriter().print(result);
}
response.close();
httpClient.close();
} catch (Exception e) {
System.err.println("HcServlet4Xxx 请求执行异常");
System.err.println(e);
}
}
}
所需依赖:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>