Специальные символы с KSOAP - PullRequest
1 голос
/ 12 апреля 2011

Я использую KSOAP2 для вызова веб-службы. Я получаю ответ, но специальные символы в нем не отображаются должным образом.

Как я могу это изменить?

EDIT:

За отправку и получение данных отвечает следующий код:

package org.ksoap2.transport;

import java.util.List;
import java.io.*;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;

import org.ksoap2.*;
import org.xmlpull.v1.*;

/**
 * A J2SE based HttpTransport layer.
 */
public class HttpTransportSE extends Transport {

    private ServiceConnection connection;

    /**
     * Creates instance of HttpTransportSE with set url
     * 
     * @param url
     *            the destination to POST SOAP data
     */
    public HttpTransportSE(String url) {
        super(null, url);
    }

    /**
     * Creates instance of HttpTransportSE with set url and defines a
     * proxy server to use to access it
     * 
     * @param proxy
     *              Proxy information or <code>null</code> for direct access
     * @param url
     *              The destination to POST SOAP data
     */
    public HttpTransportSE(Proxy proxy, String url) {
        super(proxy, url);
    }

    /**
     * Creates instance of HttpTransportSE with set url
     * 
     * @param url
     *            the destination to POST SOAP data
     * @param timeout
     *            timeout for connection and Read Timeouts (milliseconds)
     */
    public HttpTransportSE(String url, int timeout) {
        super(url, timeout);
    }

    /**
     * set the desired soapAction header field
     * 
     * @param soapAction
     *            the desired soapAction
     * @param envelope
     *            the envelope containing the information for the soap call.
     * @throws IOException
     * @throws XmlPullParserException
     */
    public void call(String soapAction, SoapEnvelope envelope) throws IOException, XmlPullParserException {

        call(soapAction, envelope, null);
    }

    /**
     * 
     * set the desired soapAction header field
     * 
     * @param soapAction
     *              the desired soapAction
     * @param envelope
     *              the envelope containing the information for the soap call.
     * @param headers
     *              a list of HeaderProperties to be http header properties when establishing the connection
     *                         
     * @return <code>CookieJar</code> with any cookies sent by the server
     * @throws IOException
     * @throws XmlPullParserException
     */
    public List call(String soapAction, SoapEnvelope envelope, List headers) 
        throws IOException, XmlPullParserException {

        if (soapAction == null)
            soapAction = "\"\"";

        byte[] requestData = createRequestData(envelope);

        requestDump = debug ? new String(requestData) : null;
        responseDump = null;

        connection = getServiceConnection();

        connection.setRequestProperty("User-Agent", "kSOAP/2.0");
        connection.setRequestProperty("SOAPAction", soapAction);
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestProperty("Connection", "close");
        connection.setRequestProperty("Content-Length", "" + requestData.length);

        // Pass the headers provided by the user along with the call
        if (headers != null) {
            for (int i = 0; i < headers.size(); i++) {
                HeaderProperty hp = (HeaderProperty) headers.get(i);
                connection.setRequestProperty(hp.getKey(), hp.getValue());
            }
        }

        connection.setRequestMethod("POST");
        connection.connect();


        OutputStream os = connection.openOutputStream();

        os.write(requestData, 0, requestData.length);
        os.flush();
        os.close();
        requestData = null;
        InputStream is;
        List retHeaders = null;

        try {
            connection.connect();
            is = connection.openInputStream();
            retHeaders = connection.getResponseProperties();
        } catch (IOException e) {
            is = connection.getErrorStream();

            if (is == null) {
                connection.disconnect();
                throw (e);
            }
        }

        if (debug) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[256];

            while (true) {
                int rd = is.read(buf, 0, 256);
                if (rd == -1)
                    break;
                bos.write(buf, 0, rd);
            }

            bos.flush();
            buf = bos.toByteArray();
            responseDump = new String(buf);
            is.close();
            is = new ByteArrayInputStream(buf);
        }

        parseResponse(envelope, is);
        return retHeaders;
    }

    public ServiceConnection getConnection() {
        return (ServiceConnectionSE) connection;
    }

    protected ServiceConnection getServiceConnection() throws IOException {
        return new ServiceConnectionSE(proxy, url);
    }

    public String getHost() {

        String retVal = null;

        try {
            retVal = new URL(url).getHost();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return retVal;
    }

    public int getPort() {

        int retVal = -1;

        try {
            retVal = new URL(url).getPort();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return retVal;
    }

    public String getPath() {

        String retVal = null;

        try {
            retVal = new URL(url).getPath();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return retVal;
    }
}

Какие строки можно изменить, чтобы применить кодировку UTF-8?

Ответы [ 3 ]

1 голос
/ 14 апреля 2011

Я обнаружил, что кодировка была не UTF-8, а ISO_8859_1.Я преобразовал входной поток в кодировке ISO_8859_1 в UTF-8, и теперь все отображается так, как должно.

0 голосов
/ 13 мая 2013

У меня похожая проблема, когда я пытаюсь отправить китайский символ на php-сервер, и сервер получает ???, я обнаружил, что это ошибка ksoap, пожалуйста, прочитайте введите описание ссылки здесь для подробностей.эта ошибка исправлена ​​в ksoap2.6.

0 голосов
/ 08 марта 2013

Старый вопрос, но если я смогу помочь кому-нибудь, я отправлю свое решение.

Подобная проблема.Я искал журналы сервера и увидел, что мой запрос был в кодировке ISO-8859-1, поэтому в ответе сервера была и эта кодировка.Мое решение было переопределить ksoap API.В классе HttpTransportSE, который вы задали в своем вопросе, в вызове метода я изменил строку:

connection.setRequestProperty("Content-Type", "text/xml");

Я хотел, чтобы мой запрос был в кодировке UTF-8, поэтому я добавил:

connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");

Теперь я отправляю запрос UTF-8 и получаю ответ UTF-8.

Надеюсь, это поможет.

...