色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

java get請求傳json

錢良釵1年前7瀏覽0評論

Java Web開發中經常采用get請求傳遞JSON數據,下面將介紹如何使用Java GET請求傳遞JSON數據。

//引入需要的包
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
//獲取JSON數據的方法
public static String getJsonData(String url) {
StringBuffer result = new StringBuffer();
try {
//創建連接對象
URL connUrl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) connUrl.openConnection();
//設置連接屬性
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setConnectTimeout(5000);
httpConn.setReadTimeout(5000);
//發送請求
httpConn.connect();
//獲取響應狀態碼
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//讀取響應數據
BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
in.close();
}
//關閉連接
httpConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}

使用上述代碼可以簡單地實現Java GET請求傳遞JSON數據的功能,需要注意的是,在請求頭中需要設置Content-Type和Accept兩個屬性,且響應數據需要進行讀取和關閉連接操作。