2017年6月27日 星期二

Java :HttpUrlConnection發送GET取得Json

Http協定是遊客戶端與伺服器建立一個TCP連線之後,客戶端發出Http請求(封包)與伺服器建立可靠的連線,伺服器在收到請求後,針對請求的內容進行處理後,在將狀態資訊發送回給客戶端,此資訊可能是客戶請求的檔案或是錯誤訊息(Json/xml格式)。

Http協定定義了12種方法提供客戶端請求至伺服器,分別為(GET,POST,HEAD,PUT,PATCH,COPY,MOVE,DELETE,LINK,UNLIKE,OPTION)最常見的方法為GET與POST。

GET與POST的差別 :
兩者的差別在於傳送封包裡的內容,Http封包內包含header(標頭)與data(資訊),header就像是信封上的地址,data就是裡面的資訊。
header:http://xxx.xxx
data:id=201

GET:把data直接加在在header後面,像是http://xxx?id=201,這種方法不適合放有安全疑慮的資訊。

POST:把header與data分開放,此方法適合有安全疑慮的資訊

程式碼(使用GET):
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonReader {
 
 public static String getJSON(String url, int timeout) throws IOException {

     URL u = new URL(url);
     HttpURLConnection c = (HttpURLConnection) u.openConnection();
     c.setRequestMethod("GET");
     c.setUseCaches(false);
     c.setAllowUserInteraction(false);
     c.setConnectTimeout(timeout);   //设置连接主机超时(单位:毫秒) 
     c.setReadTimeout(timeout);      //设置从主机读取数据超时(单位:毫秒) 
     c.setRequestProperty("User-Agent","Mozilla/5.0");
     c.connect();
     int status = c.getResponseCode();

     switch (status) {
         case 200:
         case 201:
             BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(),"utf-8"));
             StringBuilder sb = new StringBuilder();
             String line;
             while ((line = br.readLine()) != null) {
                 sb.append(line + "\n");
             }
             br.close();
             return sb.toString();
     }

     return null;
 }
    public static void main(String[] args) throws IOException {
     
     String s = getJSON("http://data.ntpc.gov.tw/od/data/api/18621BF3-6B00-4A07-B49C-0C5CCABFE026?$format=json&$filter=routeNameZh%20eq%20637",9000);
     try {
   JSONArray jsonarray = new JSONArray(s);
   JSONObject obj = jsonarray.getJSONObject(0);
   System.out.println(obj.get("latitude"));
  } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
     
    }
}

1 則留言: