java发送post请求json格式
时间: 2023-11-04 15:00:03 浏览: 69
可以使用以下代码示例发送Post请求并传递JSON格式数据:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
public class HttpURLConnectionExample {
private static final String targetURL = "http://example.com/api/test";
public static void main(String[] args) {
try {
URL url = new URL(targetURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
String jsonInputString = "{\"name\": \"John Smith\", \"email\": \"john.smith@example.com\"}";
try(OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "utf-8"));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = bufferedReader.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,此示例代码仅供参考,您需要根据实际需求进行修改。
阅读全文