java post请求代码
时间: 2024-04-14 10:19:39 浏览: 14
以下是一个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 HttpPostExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpPostExample http = new HttpPostExample();
System.out.println("Sending HTTP POST request");
String url = "http://www.example.com/api";
String params = "name=John&age=30";
String response = http.sendPost(url, params);
System.out.println("Response from server:\n" + response);
}
// HTTP POST request
private String sendPost(String url, String params) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
// Read response from server
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
在此示例中,我们通过HttpURLConnection发送了一个POST请求。我们设置了请求头,设置请求方法为POST,并将参数作为请求体发送。我们还从服务器读取了响应并将其作为字符串返回。