HTTPURLConnection返回乱码

时间:2014-03-27 19:08:34

标签: java xml

我正在修改一些工作代码以使用不同的提供商的API(我们正在切换帮助台提供商)。

我试着看看xml回来看看我是否在正确的轨道上,但我看到的所有回来都是胡言乱语。我查看了this问题,但无法弄清楚这些答案如何适用于我的情况。

如果我没记错的话,当我使用其他API时,我能够在控制台中读取回来的xml:

while ((line = br.readLine()) != null) {
    System.out.println(line);
}

我的问题是:有没有一种方法可以不同方式读取流,以便我可以读取回来的xml或者我有其他问题?

我对此很新,所以任何想法都会受到赞赏。更多详情如下。

代码:

package com.google.gwt.HelpDeskTest.server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.gwt.HelpDeskTest.client.HelpDeskTestService;
import com.google.gwt.HelpDeskTest.shared.HelpDeskTestException;


@SuppressWarnings("serial")
public class HelpDeskTestImpl extends RemoteServiceServlet implements
    HelpDeskTestService {

    @Override
    public String postToRemoteServer(String serviceUrl)
            throws HelpDeskTestException {
        try {

            final String serverPath= "https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails";

            System.out.println(serverPath);


            final String serverParameters= "<?xml version=%221.0%22 encoding=%22utf-16%22?>" + 
            "<GetTicketAction xmlns:xsi=%22http://www.w3.org/2001/XMLSchema-instance%22 xmlns:xsd=%22http://www.w3.org/2001/XMLSchema%22>" + 
            "<CompanyName>xxxxxx</CompanyName><IntegrationLoginId>xxxxxxx</IntegrationLoginId><IntegrationPassword>xxxxxx</IntegrationPassword>" +
            "<SrServiceRecid>1921</SrServiceRecid></GetTicketAction>";


            System.out.println(serverParameters);

            //Open HttpURLConnection:           

            URL url = new URL(serverPath); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();   

            connection.setConnectTimeout(10000); //added this to see if I can address the timeout issue.
            connection.setReadTimeout(10000);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("POST"); 
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            connection.setRequestProperty("charset", "utf-16");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(serverParameters.getBytes().length));
            connection.setUseCaches (false);
            //connection.setChunkedStreamingMode(0);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
            wr.writeBytes(serverParameters);
            wr.flush();
            wr.close();

            //process response - need to get xml response back.
            //this was the working line of code:
            InputStream stream = connection.getInputStream();

            //put output stream into a string
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            String result = "";
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                result+= line;
            }

            br.close();
            connection.disconnect();

            System.out.println(result);

            return result;


        }  catch (final Exception e) {
            System.out.println(e.getMessage());
            throw new HelpDeskTestException();
            //handle timeout error

        }
    }   
}

这是我试图发送的xml。我已经通过公司的API测试器对它进行了测试,并知道它可以正常工作,并通过发送xml来响应。

<?xml version="1.0" encoding="utf-16"?>
<GetTicketAction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <CompanyName>xxxxxx</CompanyName>
    <IntegrationLoginId>xxxxxx</IntegrationLoginId>
    <IntegrationPassword>xxxxx</IntegrationPassword>
    <SrServiceRecid>1921</SrServiceRecid>
</GetTicketAction>

2 个答案:

答案 0 :(得分:1)

发送数据时,请指定utf-16作为编码。

但是当您阅读响应时,您没有指定编码,因此使用默认的平台编码。

所以交换这一行:

BufferedReader br = new BufferedReader(new InputStreamReader(stream));

这个(假设响应也用utf-16编码):

BufferedReader br = new BufferedReader(new InputStreamReader(stream,"utf-16"));

您应该检查响应标头以了解已使用的编码。

答案 1 :(得分:0)

经过多次搜索,我找到了答案。 xml被读作乱码,因为它是Gzip压缩的。阅读本文的方法是使用 GZIPInputStream。这是因为XML的压缩方式不同。

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Accept-Encoding", "gzip");
        InputStreamReader in = new InputStreamReader (new GZIPInputStream(connection.getInputStream()));
        String str;            
        while (true) {
     int ch = in.read();
     if (ch==-1) {
        break;
     }