最近工作中有个任务,就是从一个接口中获取json数据完成页面的动态加载;但是在ajax调用的时候出现了跨域的问题,由于无法修改接口的请求头;所以采用java后台代码通过url获取到数据再返回相关的json数据(考虑到把json全部获取到前台,再遍历的话不仅数据量大而且逻辑会比较复杂),再又ajax调用使用;
1.主要核心:读取url,返回json串;
public String getData(String addess){
URL url = null;
HttpURLConnection httpConn = null;
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try{
url = new URL(addess);
in = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8") );
String str = null;
while((str = in.readLine()) != null) {
sb.append( str );
}
} catch (Exception ex) {
} finally{
try{
if(in!=null) {
in.close();
}
}catch(IOException ex) {
}
}
String data =sb.toString();
return data;
}
2.根据业务需要及所请求获取到的json,进行遍历获取相关的newjson数据,主要代码:
//json串转化为json对象
public JSONObject getjson(String data) {
JSONObject json = JSONObject.fromObject(data);
return json;
}
getResponse().setHeader("Content-type", "text/html;charset=UTF-8");
//获取到的json串
String s1 = null;
try {
s1 = getData("url填入请求的地址");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
//异常处理
}
JSONObject jsonobject1 = null;
JSONArray jsonarray = null;
//获取第一条json数据的标识符;
int flag01=1;
try {
//json串转化为jsonObj
jsonobject1 = getjson(s1);
JSONObject jobjects1= (JSONObject) jsonobject1.get("Response");//获取相关字段
jsonarray = jobjects1.getJSONArray("result");
} catch (Exception e2) {
// TODO Auto-generated catch block
//异常处理
}
//遍历并获取相关数据
List<String> mnList=new ArrayList();
for (int i = 0; i < jsonarray.size(); i++) {
JSONObject data=jsonarray.getJSONObject(i);
data.get("MON_NAME");
if(!mnList.contains(data.getString("MON_NAME"))){
mnList.add(data.getString("MON_NAME"));
}
}
//遍历mnlist转化为字符串
StringBuffer sb=new StringBuffer();
for (int i = 0; i < mnList.size(); i++) {
if(i!=mnList.size()-1){
sb.append(mnList.get(i)+",");}
else{
sb.append(mnList.get(i));
}
}
//创建需要的json串,部分代码省略
String myjsonstr="{\"cname\":\""+sb.toString()+"\",\"dataNum\":\""+dataNum+"\",\"okFlag\":\""+okFlag+"\",\"msg\":\""+msg+"\"}";
JSONObject myjson = getjson(myjsonstr);
JSONArray jarray=new JSONArray();
jarray.add(jsonobject1);
jarray.add(myjson);
try {
PrintWriter out = getResponse().getWriter();
out.print(jarray.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3.最后可以就通过ajax访问获取相关的数据了;