来自JAVA中的HttpURLConnection的响应产生垃圾值

时间:2015-11-11 15:35:00

标签: java

场景:我需要点击HTTPS网址来获取.csv文件或其内容。我可以使用Chrome浏览器中的高级REST客户端插件成功获取所需内容。但是在尝试使用java代码执行相同操作时获取垃圾值。

代码:

find()

即使使用POST方法,我也会得到相同的响应。谁能告诉我哪里出错或需要纠正什么。

提前致谢。

更新 根据@Hendrik Simon的回应,我可以以可读的格式获得响应。 但现在我面临另一个障碍。现在的回应是

public class AnotherBean {
    private final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36";

    public void printAnotherMessage() {
        System.out.println("I am called by Quartz jobBean using CronTriggerFactoryBean");

        AnotherBean anotherBean = new AnotherBean();

        try {
            System.out.println("Testing 1 - Send Http GET request");
            anotherBean.sendGet();
            // System.out.println("\nTesting 2 - Send Http POST request");
            // anotherBean.sendPost();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // HTTP GET request
    private void sendGet() throws Exception {
        String url = "https://xxx.xxx.com/xxxx/DownloadReport/2015/10/29/xxx/TransactionDetailReport.csv";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
        con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        con.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");

        String urlParameters = "username=xxxx&password=xxxx";

        con.setDoOutput(true);
        con.setDoInput(true);

        OutputStream wr = con.getOutputStream();
        // wr.writeBytes(urlParameters);
        wr.write(urlParameters.getBytes("UTF-8"));
        wr.flush();
        wr.close();
        // con.connect();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        System.out.println("Post parameters : " + urlParameters);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println("Response: " + response.toString());
        System.out
                .println("Content Encoding: " + con.getContentEncoding() + "\nContent Length: " + con.getContentLength()
                        + "\nContent Type: " + con.getContentType() + "\nContent: " + con.getContent());
    }

    // HTTP POST request
    private void sendPost() throws Exception {
        String url = "https://xxx.xxx.com/xxxx/DownloadReport/2015/10/29/xxx/TransactionDetailReport.csv";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        // add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
        con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        con.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");

        String urlParameters = "username=xxx&password=xxxx";
        // String urlParameters = "{" +
        // "\"username\":\"xxxx\",\"password\":\"xxxx\"" +
        // "}";

        // Send post request
        con.setDoOutput(true);
        con.setDoInput(true);
        // DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        OutputStream wr = con.getOutputStream();
        // wr.writeBytes(urlParameters);
        wr.write(urlParameters.getBytes("UTF-8"));
        wr.flush();
        wr.close();
        // con.connect();
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        // BufferedReader inputReader = new BufferedReader(new
        // InputStreamReader((InputStream) con.getContent()));
        // String theString = IOUtils.toString(con.getInputStream(),
        // StandardCharsets.UTF_16BE);
        // byte[] byteArray = IOUtils.toByteArray(con.getInputStream());
        // String theString = IOUtils.toString(byteArray);
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
            // System.out.println(" " + inputLine);
        }

        /*
         * do { inputLine = inputReader.readLine(); response.append(inputLine +
         * "\n"); } while (inputLine != null);
         */

        // String finalResponse = new String(response, StandardCharsets.UTF_8);
        // inputReader.close();

        // print result
        System.out.println("Response: " + response.toString());
        // System.out.println("Response - theString: " + theString);
        // System.out.println("Response String: " + byteArray);
        System.out
                .println("Content Encoding: " + con.getContentEncoding() + "\nContent Length: " + con.getContentLength()
                        + "\nContent Type: " + con.getContentType() + "\nContent: " + con.getContent());
    }
}


**Response:**
***Sending 'GET' request to URL :*** "https://xxx.xxx.com/xxxx/DownloadReport/2015/10/29/xxx/TransactionDetailReport.csv";
***Response Code :*** 200
***Post parameters :*** username=xxxx&password=xxxx
***Response:*** ‹ •UmoÓ0þÞ_aR!©YÓn¬Í"¡2H›?ø„.ñ%1sâ`;[â¿syiצÍ`NU;ñùîžçÎwþ‹wŸ—·ß¾\³Ôf2ø› ?F÷ÂJfžÇ\vƒú5»ÖZiÜì4RZ`QÚ ½rJ»oœvËØõF¬•ö{ûZ?¢»D«2çs–«™ÆÁ2i%%óè^×c±=÷g°]†Š¯;3ЉÈçlòºXÑéɬX-öb•[7†LÈõœ9ŸÊHp`4ä?»…Te0boµ ......
***Content Encoding:*** gzip
***Content Length:*** 761
***Content Type:*** text/html
***Content:*** sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@7c4ccb2f

当我在浏览器或REST客户端上使用相同的URL时,我通常会弹出一个窗口来输入凭据。在成功提交后,我获得了所需的数据。任何人都可以指导我如何使用JAVA代码处理这种情况吗?

1 个答案:

答案 0 :(得分:3)

似乎响应是gzip编码的,你不解压缩。

尝试删除以下行

    con.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");

<强>更新

正如@RealSkeptic正确提到的那样,如果数据是GET - 请求,则无法将数据写入连接。使用GET-Request,您必须将参数添加到URL,如下所示:

http://...?param1=bla&param2=blubb

我认为,只要您拨打con.setDoOutput(true);,无论您将其设置为请求方法,您的连接都会自动执行POST请求。所以你永远不会在你的例子中提出GET-Request。

例如,当您使用Wireshark分析流量时,可以很容易地看到。

至于服务器错误,如果不复制它就不容易分析。在不知道URL的情况下重新生成它是不可能的,至少对我而言。