【问题标题】:HTTPURLConnection returning gibberishHTTPURLConnection 返回乱码
【发布时间】:2014-03-27 19:08:34
【问题描述】:

我正在修改一些工作代码以使用不同提供商的 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>

【问题讨论】:

  • 试试connection.getContent()

标签: java xml


【解决方案1】:

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

但是当你读取响应时你没有指定编码,所以使用默认的平台编码。

所以换行:

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

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

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

您实际上应该检查响应标头以了解使用了哪种编码。

【讨论】:

  • 我会检查响应头,但我认为我们在正确的轨道上,因为我现在在运行它时收到以下错误:??????....很多很多问题分数...??????? com.google.gwt.xml.client.impl.DOMParseException:解析失败:第 1 列第 1 行出错:文档为空
  • 我在响应头中验证了编码是utf-16。我将继续并将其标记为答案并开始追踪我的其他错误!谢谢!
【解决方案2】:

所以经过大量搜索,我找到了答案。 xml 被读取为乱码,因为它是 Gzip 压缩的。阅读此内容的方法是使用 GZIP 输入流。这是因为 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;
     }

【讨论】:

    猜你喜欢
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 2012-04-13
    相关资源
    最近更新 更多