JAVA 发送包含 XML 字符串的 Post 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25104556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA Send Post Request which contains XML String
提问by Viktor Apoyan
Problem Description
问题描述
I'm trying to write a code which is sending POST request to the server. As server yet doesn't exist I can't test this part of code. With the request I must send XML as a String which look likes the string below:
我正在尝试编写一个向服务器发送 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>"
Solution
解决方案
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();
Question
问题
Is this right way to send String (XML like string) as POST request to the server?
这是将字符串(类似 XML 的字符串)作为 POST 请求发送到服务器的正确方法吗?
回答by Brett Okken
To POST a SOAP request, you would want to write the xml to the body of the request. You do not want to write it as a parameter of the request.
要发布SOAP 请求,您需要将 xml 写入请求正文。您不想将其写为请求的参数。
String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
urlConnection con = (HttpsURLConnection) obj.openConnection();
// add request 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();