java http post请求代码
时间: 2024-05-13 16:08:03 浏览: 37
java 发送带Basic Auth认证的http post请求实例代码
以下是Java中使用HttpURLConnection发送POST请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
String url = "http://example.com/api";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Request parameters
String urlParameters = "param1=value1¶m2=value2";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get response
int responseCode = con.getResponseCode();
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 result
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们使用HttpURLConnection类来与API进行通信。我们设置请求方法为POST并设置请求属性。然后我们设置请求参数并发送POST请求。最后,我们读取响应并将其打印在控制台上。
阅读全文