在使用Java發(fā)送HTTP請求時,我們經(jīng)常需要傳遞JSON數(shù)據(jù)。這個過程需要使用URL傳遞JSON數(shù)據(jù),下面介紹一下這個過程。
URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); String jsonInputString = "{\"name\": \"John\", \"age\": 30}"; conn.setDoOutput(true); try(OutputStream os = conn.getOutputStream()) { byte[] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); } try(BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8"))) { StringBuilder response = new StringBuilder(); String responseLine = null; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } System.out.println(response.toString()); }
上面的代碼中,我們首先創(chuàng)建一個URL對象,并使用它創(chuàng)建一個HttpURLConnection對象。然后我們設置請求方法為POST,并設置請求頭的Content-Type為application/json。接下來,我們創(chuàng)建JSON字符串,并將其轉(zhuǎn)換成字節(jié)數(shù)組。我們通過調(diào)用conn.getOutputStream()方法獲得OutputStream對象,然后將字節(jié)數(shù)組寫入OutputStream對象中。最后,我們獲取響應并將其轉(zhuǎn)換為字符串,以便在控制臺上輸出。