Java是一種面向?qū)ο蟮木幊陶Z言,它可以通過HTTP請求方式獲取和發(fā)送JSON數(shù)據(jù),其中GET和POST方法是最常用的兩種請求方式。
GET方法通過URL傳遞參數(shù),適用于簡單的數(shù)據(jù)請求,而POST方法則適用于請求大量數(shù)據(jù)或需要增加、修改、刪除數(shù)據(jù)等情況。
//使用GET方法獲取JSON數(shù)據(jù)示例 import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; public class GetJsonData { public static void main(String args[]) { try { URL url = new URL("http://example.com/data.json"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode != 200) { throw new RuntimeException("HTTP GET請求失敗:" + responseCode); } else { Scanner scanner = new Scanner(conn.getInputStream(), "UTF-8"); StringBuffer jsonStr = new StringBuffer(); while (scanner.hasNextLine()) { jsonStr.append(scanner.nextLine()); } scanner.close(); conn.disconnect(); System.out.println(jsonStr.toString()); } } catch (Exception e) { e.printStackTrace(); } } }
//使用POST方法發(fā)送JSON數(shù)據(jù)示例 import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class PostJsonData { public static void main(String args[]) { try { URL url = new URL("http://example.com/data.json"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); String json = "{ \"name\":\"John\", \"age\":30 }"; OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); osw.write(json); osw.flush(); osw.close(); int responseCode = conn.getResponseCode(); if (responseCode != 200) { throw new RuntimeException("HTTP POST請求失敗:" + responseCode); } else { System.out.println("POST請求成功!"); } } catch (Exception e) { e.printStackTrace(); } } }
在使用GET和POST方法獲取和發(fā)送JSON數(shù)據(jù)時,需要注意請求頭的Content-Type屬性,以及需要進(jìn)行異常處理。