Java中使用POST請(qǐng)求發(fā)送JSON數(shù)據(jù)時(shí),需要在請(qǐng)求頭信息中設(shè)置Content-Type為application/json;charset=utf-8,并且將JSON數(shù)據(jù)放在請(qǐng)求體中傳輸。
//創(chuàng)建連接 URL url = new URL("https://www.example.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //設(shè)置請(qǐng)求方式和請(qǐng)求頭信息 connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); //設(shè)置請(qǐng)求參數(shù) JSONObject requestData = new JSONObject(); requestData.put("name", "張三"); requestData.put("age", 20); //發(fā)送請(qǐng)求 connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestData.toString().getBytes()); outputStream.flush(); outputStream.close(); //獲取響應(yīng)結(jié)果 int responseCode = connection.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); //解析響應(yīng)結(jié)果 //...... inputStream.close(); }
在請(qǐng)求參數(shù)較多的情況下,建議使用POJO對(duì)象來管理請(qǐng)求參數(shù),然后使用JSON數(shù)據(jù)進(jìn)行序列化和反序列化。
//請(qǐng)求參數(shù)對(duì)象 public class User { private String name; private int age; //getter和setter方法 } //請(qǐng)求參數(shù)序列化為JSON數(shù)據(jù) User requestUser = new User(); requestUser.setName("張三"); requestUser.setAge(20); String requestData = new ObjectMapper().writeValueAsString(requestUser); //發(fā)送請(qǐng)求 connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestData.getBytes()); outputStream.flush(); outputStream.close(); //響應(yīng)結(jié)果反序列化為對(duì)象 InputStream inputStream = connection.getInputStream(); User responseUser = new ObjectMapper().readValue(inputStream, User.class);
以上就是Java中使用POST請(qǐng)求發(fā)送JSON數(shù)據(jù)的方法,開發(fā)者可以根據(jù)實(shí)際需求進(jìn)行相應(yīng)調(diào)整。