3.阿里巴巴提供了接口,但不支持js跨域请求回调,我们可以在java代码中请求,返回参数:
//工具类
public class ResponseUtil {
public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.Callable;
public class IPLocationTask implements Callable<Map<String, String>> {
private String id;
private String uri;
private String type;
public IPLocationTask(String id,String type, String url) {
super();
this.id = id;
this.uri = url;
this.type = type;
}
@Override
public Map<String, String> call() throws Exception {
URL url=new URL(uri);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(10*1000);
conn.setRequestMethod("GET");
InputStreamReader inStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
BufferedReader buffer=new BufferedReader(inStream);
String inputline=null;
String info="";
while((inputline=buffer.readLine())!=null){
info+=inputline;
}
System.out.println(type+"=="+info);
return IPLocationParseUtil.parse(type, info);
}
}
private String id;
private String uri;
private String type;
public IPLocationTask(String id,String type, String url) {
super();
this.id = id;
this.uri = url;
this.type = type;
}
@Override
public Map<String, String> call() throws Exception {
URL url=new URL(uri);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(10*1000);
conn.setRequestMethod("GET");
InputStreamReader inStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
BufferedReader buffer=new BufferedReader(inStream);
String inputline=null;
String info="";
while((inputline=buffer.readLine())!=null){
info+=inputline;
}
System.out.println(type+"=="+info);
return IPLocationParseUtil.parse(type, info);
}
}
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
public class IPLocationParseUtil {
/**
* 解析 各ip查询提供 服务的返回结果
* @param type
* @param result
* @return
*/
public static Map<String, String> parse(String type,String result){
if(StringUtils.isEmpty(result)){
Map<String, String> error=new HashMap<String, String>();
error.put("status", "error");
error.put("msg", "exception");
return error;
}
Map<String, String> map=new HashMap<String, String>();
map.put("type", type);
switch (type) {