1. 程式人生 > >Java實現Web Api介面遠端呼叫

Java實現Web Api介面遠端呼叫

package com.watering.as.web.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;

public class WebApiReturnJson {

    public static void main(String[] args) throws Exception {  
        
 
        //定義變數屬性 後期可採用動態獲取

        String dataCode = "NAFP_NWFD_SCMOC";
        String time = "201711231000";
        double minLon = 116.21;
        double maxLon = 116.45;
        double minLat = 41.17;
        double maxLat = 41.33;
        String fcstLevel = "-";
        String fcstEle = "ERH";
        int validTime = 12;
        
        //外介面URL路徑拼接

        String urlStr = "http://api.data.cma.cn:8090/api"
                + "?userId=Jlkj_jlkj_user"
                + "&pwd=123456"
                + "&interfaceId=getNafpEleGridInRectByTimeAndLevelAndValidtime"
                + "&dataCode=" + dataCode
                + "&time=" + time
                + "&minLon=" + minLon
                + "&maxLon=" + maxLon
                + "&minLat=" + minLat
                + "&maxLat=" + maxLat
                + "&fcstLevel=" + fcstLevel
                + "&fcstEle=" + fcstEle
                + "&validTime=" + validTime
                + "&dataFormat=json".replace(" ","");
        //連結URL  

        URL url=new URL(urlStr);  
        //返回結果集  
        StringBuffer document = new StringBuffer();  
        //建立連結  
        URLConnection conn = url.openConnection();  
        //讀取返回結果集  
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));  
        String line = null;  
        while ((line = reader.readLine()) != null){  
              document.append(line);  
        }     
            reader.close();  
 
        JSONObject json =JSONObject.fromObject(document.toString()); 

        //獲取json中某個物件  

        String str =(String)json.get("requestParams");
        System.out.println(str);
        
        //由於requestParams包含全部str字串資料,現將str轉Map
        String[] strs = str.split("&");
        Map<String, String> m = new HashMap<String, String>();
        for(String s:strs){
        String[] ms = s.split("=");
        m.put(ms[0], ms[1]);
        }
        System.out.println(m.get("minlon"));
        
        //獲取json串中具體值  後期可根據key隨意調取存入資料庫
        String obj = (String)json.get("requestTime");  
        System.out.println(obj);
        
    }  
}

Web Api 介面呼叫大同小異 , 各位看客可參考此類 , 希望對各位有幫助

如有更好的建議 , 請與我聯絡

本人郵箱 : [email protected]