Java 如何在 SOAP 请求中设置字符编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33752787/
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
How to set character encoding in SOAP request
提问by raz3r
I am calling a SAP SOAP Service from a web servlet in Java. For some reason SAP is giving me an error every time I use special characters in the fields of my request such as 'è' or 'à'. The WSDL of the SOAP Service is defined in UTF-8 and I have set my character encoding accordingly as you can see below. However I am not sure this is the correct way. Also, notice that if I use SOAP UI (with the same envelope) the request works correctly so it must be something on Java side.
我正在从 Java 中的 Web servlet 调用 SAP SOAP 服务。出于某种原因,每次我在请求的字段中使用特殊字符(例如“è”或“à”)时,SAP 都会给我一个错误。SOAP 服务的 WSDL 是用 UTF-8 定义的,我已经相应地设置了我的字符编码,如下所示。但是我不确定这是正确的方法。另外,请注意,如果我使用 SOAP UI(具有相同的信封),则请求可以正常工作,因此它必须是 Java 端的内容。
URL url = new URL(SOAP_URL);
String authorization = Base64Coder.encodeString(SOAP_USERNAME + ":" + SOAP_PASSWORD);
String envelope = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:soap:functions:mc-style'><soapenv:Header/><soapenv:Body><urn:ZwsMaintainTkt><item>à</item></urn:ZwsMaintainTkt></soapenv:Body></soapenv:Envelope>";
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(SOAP_TIMEOUT);
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "text/xml; charset=utf-8");
con.setRequestProperty("SOAPAction", SOAP_ACTION_ZWSMANTAINTKT);
con.setRequestProperty("Authorization", "Basic " + authorization);
con.setDoOutput(true);
con.setDoInput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
outputStreamWriter.write(envelope);
outputStreamWriter.close();
InputStream inputStream = con.getInputStream();
采纳答案by piet.t
Since a soap-request is xml use the xml-header to specify the encoding of your request:
<?xml version="1.0" encoding="UTF-8"?>
new OutputStreamWriter(con.getOutputStream())
uses the platform-default encoding which most probably is some flavour of ISO8859. Usenew OutputStreamWriter(con.getOutputStream(),"UTF-8")
instead
由于soap-request 是xml,因此请使用xml-header 来指定请求的编码:
<?xml version="1.0" encoding="UTF-8"?>
new OutputStreamWriter(con.getOutputStream())
使用平台默认编码,这很可能是 ISO8859 的某种风格。使用new OutputStreamWriter(con.getOutputStream(),"UTF-8")
替代