【发布时间】:2014-09-26 02:14:03
【问题描述】:
问题描述
我正在尝试编写一个向服务器发送 POST 请求的代码。由于服务器还不存在,我无法测试这部分代码。根据请求,我必须将 XML 作为字符串发送,如下所示:
String XMLSRequest = "<?xml version="1.0" encoding="UTF-8" standalone="no"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header><AuthenticationHeader><Username>Victor</Username><Password>Apoyan</Password></AuthenticationHeader></soapenv:Body></soapenv:Envelope>"
解决方案
String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = String.format("request=%s", XMLSRequest);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
问题
这是将字符串(类似 XML 的字符串)作为 POST 请求发送到服务器的正确方法吗?
【问题讨论】:
-
首先您需要序列化为 JSON,然后通过 HTTP 发送。
-
不知道为什么要将“request=”附加到 XML 中,除了看起来没问题。
-
@RomanC 你能举一些例子来回答如何以正确的方式通过http连接发送XML字符串吗?
-
@kharyam 你的意思是
String urlParameters = XMLSRequest;这可以吗? -
你不应该使用http连接。
标签: java xml post xmlhttprequest http-post