我在我的回复中得到了奇怪的符号而不是实际的文本

时间:2011-12-18 23:11:40

标签: java android web-services response

我在android中有SoapBuilder类调用Web服务。现在我在之前的应用程序中使用它并且它工作得很好。这个新应用程序的问题在于,我没有得到实际的响应,而是看起来像某种翼形符号。我的web服务是像我的其他应用程序一样的.net webservice。我能看到的唯一区别是我在之前的应用程序上使用ssl而现在我不是。所以我将所有套接字ssl更改为reg套接字和socketfactorys。这是我的代码我在阅读时遇到了奇怪的符号(bufferedreader)StringBuilder contentBuilder = new StringBuilder(contentLength);

if (contentLength > 0) {
    int readBytes = 0;
    int c = -1;
    while ((c = in.read()) != -1) {
        contentBuilder.append((char) c);
        readBytes++;
    }
}           

以下是SoapBuilder的完整代码。

public class SoapBuilder {
    private final String TAG = "SOAPBUILDER";
    String Server = SQBApplication.SOAP_SERVER;
    String WebServicePath = SQBApplication.SOAP_WEBSERVICEPATH;
    String SoapAction = "";
    String MethodName = "";
    String XmlNamespace = SQBApplication.SOAP_XMLNAMESPACE;
    Integer Port = SQBApplication.SOAP_PORT;
    Integer BufferSize = 2048;
    // boolean IsSSL = true;
    private ArrayList<String> ParamNames = new ArrayList<String>();
    private ArrayList<String> ParamData = new ArrayList<String>();

    public SoapBuilder(String soapMethod) {
        MethodName = soapMethod;
        SoapAction = XmlNamespace + MethodName;
    }

    public SoapBuilder(String server, String soapMethod)
    {
        MethodName = soapMethod;
        SoapAction = XmlNamespace + MethodName;
        Server = server;
    }

    public SoapBuilder(String server, String webServicePath, String namespace, String soapMethod)
    {
        MethodName = soapMethod;
        XmlNamespace = namespace;
        SoapAction = XmlNamespace + MethodName;
        Server = server;
        WebServicePath = webServicePath;
    }

    public void AddParameter(String Name, String Data) {
        ParamNames.add(Name);
        ParamData.add(Data);
    }

    public String sendRequest() throws Exception {
        String retval = "";
        String message = "";

        StringBuilder postAction = new StringBuilder();
        // send an HTTP request to the web service
        postAction.append("POST " + WebServicePath + " HTTP/1.1\n");
        postAction.append("Content-Type: text/xml; charset=utf-8\n");
        postAction.append("SOAPAction: \"" + SoapAction + "\"\n");
        postAction.append("Host: " + Server + ":" + Port + "\n");
        postAction.append("Content-Length: %s\n");
        postAction.append("Expect: 100-continue\n");
        postAction.append("Accept-Encoding: gzip, deflate\n");
        postAction.append("Connection: Close\n");
        postAction.append("\n");
        ArrayList<String> envelope = new ArrayList<String>();
        envelope.add("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        envelope.add("<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
        envelope.add("<" + MethodName + " xmlns=\"" + XmlNamespace + "\">");
        // Parameters passed to the method are added here
        for (int t = 0; t < ParamNames.size(); t++) {
            String name = (String) ParamNames.get(t);
            String data = (String) ParamData.get(t);
            envelope.add("<" + name + ">" + data + "</" + name + ">");
        }
        envelope.add("</" + MethodName + ">");
        envelope.add("</s:Body>");
        envelope.add("</s:Envelope>");

        int si = 0;
        for (int i = 0; i < envelope.size(); i++) {
            si += envelope.get(i).length();
        }

        StringBuilder bodyBuilder = new StringBuilder(si);
        for (int i = 0; i < envelope.size(); i++) {
            bodyBuilder.append(envelope.get(i));
        }
        message = String.format(postAction.toString(),
        Integer.toString(bodyBuilder.length()));
        message += bodyBuilder.toString();
        Socket socket = null;
        boolean autoflush = true;
        try {
            SocketFactory socketFactory = (SocketFactory) SocketFactory
                .getDefault();
            socket = (Socket) socketFactory.createSocket(Server, Port);
            PrintWriter out = new PrintWriter(socket.getOutputStream(),
            autoflush);

            System.out.println("request length: " + message.length());
            if(message.length() > Integer.MAX_VALUE)
            {
                throw new IOException("message length exceeds max size");
            }
            socket.setSendBufferSize(message.length());
            //only except if the message wouldn't have succeeded anyway
            if(socket.getSendBufferSize() < message.length() && socket.getSendBufferSize() != message.length())
            {
                throw new Exception();
            }

            out.print(message);
            out.flush();

        } catch (Exception e) {

        }

        BufferedReader in = new BufferedReader(new InputStreamReader(
        socket.getInputStream(), "UTF-8"), BufferSize);
        StringBuilder response = new StringBuilder();

        int ci;

        Pattern httpPattern = Pattern.compile(
            "HTTP/1.\\d\\s+(\\d+)\\s+[\\w\\s]+\\r\\n",
            Pattern.CASE_INSENSITIVE);
        Pattern contentLengthPattern = Pattern.compile(
            "Content-Length\\:\\s*(\\d+)\\r\\n",
            Pattern.CASE_INSENSITIVE);
        int contentLength = -1;
        String httpResponse = "";
        while ((ci = in.read()) != -1) {
            response.append((char) ci);
            Matcher lengthMatcher = contentLengthPattern.matcher(response
                .toString());
            Matcher httpMatcher = httpPattern.matcher(response.toString());

            if (lengthMatcher.find()) {
                contentLength = Integer.parseInt(lengthMatcher.group(1));
            }
            if (httpMatcher.find()) {
                httpResponse = httpMatcher.group(1);
            }

            if (contentLength > 0) {
                // contentLength+=2;
                break;
            }
        }

        StringBuilder contentBuilder = new StringBuilder(contentLength);
        if (contentLength > 0) {
            int readBytes = 0;
            int c = -1;
            while ((c = in.read()) != -1) {
                contentBuilder.append((char) c);
                readBytes++;
            }

        }

        System.out.println(httpResponse);
        if (httpResponse.equals("200")) {

            Pattern responsePattern = Pattern.compile(
                "<soap:Envelope.*?>(.+)</soap:Envelope>",
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL
                | Pattern.MULTILINE);

            Pattern responseNullPattern = Pattern.compile("<" + MethodName
                + "Response.+?/>", Pattern.CASE_INSENSITIVE
                | Pattern.DOTALL | Pattern.MULTILINE);
            Matcher responseMatcher = responsePattern
                .matcher(contentBuilder);
            Matcher responseNullMatcher = responseNullPattern
                .matcher(contentBuilder);
            System.out.println(contentBuilder);
            if (responseMatcher.find()) {
                retval = responseMatcher.group(0);// responseMatcher.group(0);
            } else if (responseNullMatcher.find()) {
                retval = null;
            }
        } else if (httpResponse.equals("500")) {
            Pattern faultPattern = Pattern.compile(
                "<soap.Fault.+?>(.+)</soap.Fault>",
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL
                | Pattern.MULTILINE);
            Matcher faultMatcher = faultPattern.matcher(contentBuilder);
            faultMatcher.find();
            retval = faultMatcher.group(0);
        } else {
            throw new Exception(String.format(
                "HTTP response not recognized: %s", httpResponse));
        }

        in.close();
        socket.close();
        return retval;
    }
}

1 个答案:

答案 0 :(得分:0)

我几乎可以保证这是一个编码问题。 Wycats写了一篇很好的文章,你应该阅读(忽略Ruby特异性):

http://yehudakatz.com/2010/05/05/ruby-1-9-encodings-a-primer-and-the-solution-for-rails/