Java 发送包含 JSON 数据的 POST 请求 - 代码示例
可以使用以下代码示例来发送一个包含 JSON 数据的 POST 请求:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
public class PostJsonExample {
public static void main(String[] args) {
String url = 'http://example.com/api/endpoint';
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put('id', 123);
jsonMap.put('name', 'John Doe');
Gson gson = new Gson();
String json = gson.toJson(jsonMap);
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod('POST');
con.setRequestProperty('Content-Type', 'application/json');
con.setDoOutput(true);
con.getOutputStream().write(json.getBytes('UTF-8'));
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = '';
String inputLine;
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
in.close();
System.out.println('Response: ' + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例中,我们使用了 Google 的 Gson 库来将一个 Map 转换为 JSON 字符串。然后,我们设置请求的 Content-Type 为 application/json,并将 JSON 数据作为请求的 body 发送。最后,我们读取响应并将其打印到控制台。
请注意,这个示例中的代码并没有对异常进行处理,实际应用中需要根据具体情况进行处理。
原文地址: https://www.cveoy.top/t/topic/lBaI 著作权归作者所有。请勿转载和采集!