How to set character encoding in SOAP request

37,543
  1. Since a soap-request is xml use the xml-header to specify the encoding of your request:

    <?xml version="1.0" encoding="UTF-8"?>

  2. new OutputStreamWriter(con.getOutputStream()) uses the platform-default encoding which most probably is some flavour of ISO8859. Use new OutputStreamWriter(con.getOutputStream(),"UTF-8") instead

Share:
37,543
raz3r
Author by

raz3r

:)

Updated on November 18, 2020

Comments

  • raz3r
    raz3r over 3 years

    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.

    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();
    
  • raz3r
    raz3r over 8 years
    Seems to work! I'll do some more tests and then I'll mark the question as answered. Many thanks.