Java发HTTP POST请求(内容为xml格式)
时间: 2024-02-03 12:04:33 浏览: 67
你可以使用Java中的HttpURLConnection类来发送HTTP POST请求,并将内容设置为XML格式。以下是一个示例代码:
```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();
String url = "http://example.com/api";
String xml = "<data><name>John</name><age>30</age></data>";
http.sendPost(url, xml);
}
// HTTP POST request
private void sendPost(String url, String xml) 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("Content-Type", "application/xml");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(xml);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post Data : " + xml);
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 result
System.out.println(response.toString());
}
}
```
在上面的示例中,我们首先创建了一个`HttpPostExample`类,并在`main`方法中调用了`sendPost`方法,该方法将URL和XML内容作为参数传递。
在`sendPost`方法中,我们首先创建一个URL对象,并使用`HttpURLConnection`类打开连接。然后,我们设置请求头,包括请求方法,User-Agent和Content-Type。接下来,我们将`doOutput`设置为`true`,以便可以向服务器发送数据。我们使用`DataOutputStream`将XML内容写入输出流中。最后,我们获取响应代码和响应正文,并将其打印出来。
阅读全文