我正在尝试编写一个向服务器发送POST请求的代码。由于服务器尚不存在,我无法测试这部分代码。根据请求,我必须将XML作为String发送,它看起来像下面的字符串:
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();
这是将String(像字符串一样的XML)作为POST请求发送到服务器的正确方法吗?
答案 0 :(得分:4)
要发布SOAP request,您需要将xml写入请求正文。你不想把它写成参数。
String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
urlConnection 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");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream()); //get output Stream from con
os.write(XMLSRequest.getBytes("utf-8");
os.close();