java 访问 太平洋网ip接口,解决前端js 跨域访问失败问题

前端 js访问太平洋网IP接口地址,返回结果是403 服务器拒绝处理异常,

于是,想到了使用 服务器端访问,然后再将查询结果返回的前端

这是Java的测试源码,【具体的contronller端源码懒得写,其实基本一样】:

 1 public class GetLocationByIP {
 2     @Test
 3     public void IpUtils(){
 4         String ip = "223.73.101.129";
 5         System.out.println(SendGET(ip));
 6     }
 7 
 8   public static String SendGET(String ip){
 9        
10      String tpy = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip="+ip;
11         //访问返回结果
12         String result="";
13         //读取访问结果
14         BufferedReader read=null;
15 
16         try {
17             //创建url
18             URL realurl=new URL(tpy);
19             //打开连接
20             URLConnection connection=realurl.openConnection();
21             // 设置通用的请求属性
22             connection.setRequestProperty("accept", "*/*");
23             connection.setRequestProperty("connection", "Keep-Alive");
24             connection.setRequestProperty("user-agent",
25                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
26             //建立连接
27             connection.connect();
28 
29             // 获取所有响应头字段
30             Map<String, List<String>> map = connection.getHeaderFields();
31 
32             // 遍历所有的响应头字段,获取到cookies等
33             for (String key : map.keySet()) {
34                 System.out.println(key + "--->" + map.get(key));
35             }
36 
37             // 定义 BufferedReader输入流来读取URL的响应
38             read = new BufferedReader(new InputStreamReader(
39                     connection.getInputStream(),"gbk"));
40             String line;//循环读取
41             while ((line = read.readLine()) != null) {
42                 result += line;
43             }
44         } catch (IOException e) {
45             e.printStackTrace();
46         }finally{
47             if(read!=null){//关闭流
48                 try {
49                     read.close();
50                 } catch (IOException e) {
51                     e.printStackTrace();
52                 }
53             }
54         }
55         return result;
56     }
57 }
View Code

测试截图:

缺点:需要指定ip参数,否则查询的则是服务器网络的公网IP, 速度相对较慢,因为速度与服务器运算速度和网络波动有很大关系 ,因此不太提倡使用。

优点:无跨域问题。

原文地址:https://www.cnblogs.com/c2g5201314/p/12246034.html