发送请求不支持post java
时间: 2023-11-07 19:04:27 浏览: 44
对于Java,发送POST请求需要使用HttpURLConnection或者HttpClient库。以下是一个使用HttpURLConnection发送POST请求的示例代码:
```
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String data = "param1=value1¶m2=value2";
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
```
需要注意的是,发送POST请求需要设置请求方法为POST,同时设置setDoOutput为true,以便向服务器发送请求体。请求体可以使用OutputStreamWriter写入,格式为key=value的形式,多个参数使用&连接。
如果需要发送JSON格式的请求体,可以使用以下代码:
```
String json = "{\"key\":\"value\"}";
conn.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(json);
writer.flush();
```
以上代码设置请求头Content-Type为application/json,然后将JSON格式的请求体写入OutputStreamWriter。