java post请求代码
时间: 2024-04-14 18:19:27 浏览: 54
以下是使用 Java 发送 POST 请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) {
String url = "http://example.com/api/endpoint";
String data = "param1=value1¶m2=value2";
try {
URL endpoint = new URL(url);
HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
}
BufferedReader responseReader = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("Output from Server:\n");
while ((output = responseReader.readLine()) != null) {
System.out.println(output);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,`url` 和 `data` 分别表示请求的 URL 和请求参数。我们使用 `HttpURLConnection` 类来发送请求,并设置请求方法为 `POST`。设置请求头的 `Content-Type` 为 `application/x-www-form-urlencoded`,表示请求参数为表单形式。然后,我们将请求参数写入输出流,并发送请求。最后,我们读取响应数据,并在控制台打印出来。
阅读全文