JSON(JavaScript Object Notation)是一種輕量級的數據交換格式。Java通過使用類庫可以方便地操作JSON,同時發送JSON格式的請求也成為了Web開發必不可少的技能之一。
在Java中發送JSON請求,需要使用HttpURLConnection或者HttpClient這兩種方式。
(一)使用HttpURLConnection發送JSON請求
try { URL url = new URL("http://www.example.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); String jsonInputString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}"; try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); } try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) { StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } System.out.println(response.toString()); } connection.disconnect(); } catch (IOException e) { e.printStackTrace(); }
以上代碼中,首先創建一個URL對象,設置請求方法為POST,添加請求頭中的Content-Type和Accept,同時設置允許輸出請求正文內容。接著,將JSON字符串寫入輸出流中,再通過輸入流獲取響應代碼,最后斷開連接。
(二)使用HttpClient發送JSON請求
CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.example.com/api"); httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Accept", "application/json"); String jsonInputString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}"; StringEntity entity = new StringEntity(jsonInputString, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); HttpResponse httpResponse = client.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); String responseString = EntityUtils.toString(httpEntity, "UTF-8"); System.out.println(responseString); client.close();
以上代碼中,首先創建一個CloseableHttpClient對象,然后創建HttpPost對象并設置請求URL、Content-Type和Accept。接著,將JSON字符串寫入實體中,并將實體設置到HttpPost對象中,最后執行HttpPost請求獲取響應內容并關閉HttpClient對象。