1. 程式人生 > >java使用後臺程式碼訪問介面並返回需要的json資料

java使用後臺程式碼訪問介面並返回需要的json資料

最近工作中有個任務,就是從一個介面中獲取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訪問獲取相關的資料了;