java发送post json数据
时间: 2023-07-28 11:08:17 浏览: 98
以下是使用Java发送POST请求并发送JSON数据的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostJsonExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/endpoint";
String jsonInputString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(jsonInputString.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print response
System.out.println(response.toString());
}
}
```
在上面的示例中,我们使用HttpURLConnection类来创建一个HTTP POST请求,并将JSON数据作为请求正文发送。然后,我们可以读取响应并把它打印出来。请注意,在设置请求头时,我们设置了Content-Type为application/json,这样服务器就知道我们发送的是JSON数据。
阅读全文