前端调用第三方接口跨域问题
百度了好久,大部分的文章都前篇一律的说jsonp跨域,要不就是说配置CROS。看到那种文章出处应该都是一家,心好累。首先来说淘宝目前的接口是不支持jsonp请求的,配置CROS更是无稽之谈。
首先想到的是反向代理(https://blog.youkuaiyun.com/weixin_42997826/article/details/90754275 具体见这篇文章),发现可以解决问题,布好服务。正在想今天晚上下班吃什么的时候,问题来了,服务器是https请求链接,而请求的第三方接口是http,换好https链接问题又来了,https用nginx代理报错404,哦no。看来今天晚上是下不了班了。
原链跨域,jsonp不支持,CROS没法配置,nginx也挂了,就在这山穷水尽之时(问了下大佬),说让服务器做代理转发,然后再处理数据!!!深受启发,开个接口什么操作不用,把url传过去让服务器请求,再把返回值返回到页面。
上代码
我这里是用的APIman做的模拟请求
package com.lmm.controller;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
@RestController
@RequestMapping("/test")
public class TestController {
@ResponseBody
@RequestMapping(value = "/corss", method = RequestMethod.POST,consumes="application/json")
public String sendGet(@RequestBody String dest_url, HttpServletRequest request) {
//解析json
JSONObject paramterJson = JSONObject.parseObject(dest_url);
dest_url = paramterJson.getString("dest_url");
String result = "";
BufferedReader in = null;
try {
String urlNameString = dest_url;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setReadTimeout(1000 * 3000);//设置超时时间(测试接口所以时间长一些)
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.err.println("发送GET请求出现异常:" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
}
到这步请求就出来了。
是不是有种恍然大悟的感觉?一起加油吧。想把错误都贴出来,结果发现没截图保存,这样吧,跨域无非那么几个错误404 缺少报头 返回信息不准确(emmm严格来说是请求参数不对,也无伤大雅)。见都见烦了,少见一次也蛮好的。