Domanda

Here is my Java code to get some information from stackexchange.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class StackExchangeConnect {

    private static final String URL = "http://api.stackexchange.com/2.2/answers?key=U4DMV*8nvpm3EOpvf69Rxw((&site=stackoverflow&fromdate=1396310400&todate=1398729600&order=desc&sort=activity&filter=default";

    public static void main(String[] args) throws Exception {

        StackExchangeConnect http = new StackExchangeConnect();

        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();

    }

    // HTTP GET request
    private void sendGet() throws Exception {

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(URL);

        // add request header
        request.addHeader("Accept", "application/json");

        HttpResponse response = client.execute(request);

        System.out.println("Response Code : "
                + response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(new InputStreamReader(response
                .getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());

    }

}

I am getting following in my console.

Testing 1 - Send Http GET request
Response Code : 200
�

I tried writing the contents to file, and it's like

�\00\00\00\00\00\00�Z�n�H�Cy�;_�`df1��&���.F�ٔK���|I���eƒ�M�,GO�Ev��:U�_gE����_g���U����ʭ7�i�r5���t��]uUd�ʤZW����]���n\���l]�y�pW���[�uӬ�$���;�W��4�:��2��&��:�6�L�N8�2���)�,18?ԯ1Q���E�VMa�ի����_�1�-+���<\�̲}��sS��E��^�co�[W��{y;�:f�n�NgE}e�u��r��E�Ng�-+x8����{S���Uf���V�c!�`wY�xl�r݂n�����әY�w��J�.��quw�h��v\00�0!�`"�k𘀩��U����q�i�:��L�$C4�y���Se�6��Y�hȆ�%u�5��F�0b�̓�P�0��՘�b�*�x������b�����+λ�;/��M���?�����z>@2�1g^���S���ӏ9y��.�ͪ]�v!��F��h/��&�/�I^D3ċ!��6dI�0\00l�a� �S���B��8�q�P���h�   �H<�ݼ��g�^|.����y���G/���c�\00u2a���LQ�����_ņ=ů7w�A?�Ĵ>�$%X� �͇f��Ib�%AA�_8���T����(C�����S�,�Y��A�nYu<K��$��1y��(\00Rg�E�6��Lx�B@���d&x#�->����(?^�pu�^M�粹6����-0�X@�q'���l9���'��~`�&J�}`\'"E,�ڦFJJ�^�>�H*r�q��ܦVZ�X�[ vtzKAn��g�nG ���!�z��:HJ:�oPH�oiFH�m11rt���L@i\00$όu�  'J��+�,KU4fs[5e������vh�� h��K+��4�T>�!*,���JH2.��>$�rC�)�9�!�3k��eee�O��2�`�N�ݯ]���~^ɦ}@��g��>rM��LT�Ѡ\00�m�8�Z�&�z����L�]�j.Ք�8Z�g�3(!�U�a��D\�#��Y�G�m�^lV��&�o��G�cGu���e|���8��(:\9��D&,�T������O���8y�����OQ��|�L�{\00PR�l>\000�d�"����!J�Pa%A�vs����!��j�2�p�3ąS�aĴ��M���&�B�A���9,Dx���b�,�)�&��mI�2]��g9M2F K&s�5��+����5���++xc4\�Ԓy��|ĘV�l�2b�3���D%��m!`㇇7�f}}���K��[(�4���d]�fS���^�~��ֿ}����=��ɶ��kY(�"��|]p��m�2�4DA�����3$��tѩ�j*�T�Y���    Џ.齦W�lzٹ%���Y �(d�@���P���m���{�-"���T)�(IS�n��)}��!I����bq@���O��1a*��0ؼ�("��C}9�<LNۖ�B0�ڮС�qŹ�0�e�N%#.�X  ���F�+�kS�h�3K�i��$bd"��@H�H5�)F=�DL�r�r���E�������<ٶ^e�{8�x���(oب�F��� g���]�B�l�6/��Q�gR`O�g��p%1s�I[�G���Ooq�J8�*(m榮��ӏ9�TP�������ᬳ�Z�w[1{��P���`�s�Kn���HG�3�p��Kᣦ����$2�9v1f5U����Ɲ�x�!~K��[����c�Li�˽ͧҰ�|�G(x�J��)��vk��N{s��?~{�F�N>�|�/�G�q������\uF�OƵ���<}��؇q�٭�p�K�8�RN��I�\00�b�" W,�q$�z��[v��ɶ�1hu�\00Z���"�G�c�����C"���>  ��#�(ÿ��4��$���e$%qb)C9�^������r��h��i%�����`�!��Y�b�;<B���f;�P�����쮎7��r�{A�Ru��ܬ6l&t�M��ۤ^�ӊ�0���$B���C�)Ti{��)9��    刋�U�ζ��,�Tk����'������o�u�L6��Y=x?_�I.C���\ ����S�"0�����Fi�d�f{V�R��V���j#e�s-�Ny�s�3���.���4��X�7:�&u����H%oy��km�(U�O����\B�?N<x�)���j_L'���[%�5ÔZ��J�4��9�hR�\����0�d����M��櫐8�T�P��}�aE[%N<�"v>a��������[�T�ɫ�nV��L|nw��=�,��f�����X��:�]�!�,�� hƩ<t�`�CT��r =O�CiNS��pim�����-��T7����@'�֩��({=>�K���C1<���Ngצ�Zv#꿡?7ec����@�o�Tni�U���.�C���Ý�=1\00\00

When I try the same URL in browser it's getting the JSON. If I try other URL in program, it's getting the JSON properly. Why is that?

And also, is there any Java API so that the JSON String I can convert to some Object?

NOTE:

Apache HTTP Client - 4.3.3, Apache HTTP Core - 4.3.2, Commons logging - 1.1.3

UPDATE 1

I am printing response. System.out.println(response.toString()); And I am getting the following output.

HTTP/1.1 200 OK [Cache-Control: private, Content-Type: application/json; charset=utf-8, Content-Encoding: gzip, Access-Control-Allow-Origin: *, Access-Control-Allow-Methods: GET, POST, Access-Control-Allow-Credentials: false, Date: Tue, 29 Apr 2014 06:31:45 GMT, Content-Length: 2551]
È stato utile?

Soluzione 2

The content being returned is gzip compressed. you can see this in your output of the response:

... Content-Encoding: gzip ...

Given that you're using the 4.3.3 version of the Apache HTTP client library, you simply need to do the following:

HttpClient client = HttpClientBuilder.create().build();

This will construct a HttpClient that has no problem decompressing the content, and you will get the JSON you're expecting ( The DefaultHttpClient does not support compression.)

Altri suggerimenti

It looks like it's compressed, w hich should be handled by HTTPClient; try using the builder and disabling compression.

The content is gzipped. You can verify that using

 System.out.println(connection.getContentEncoding());

To get the content, use something like this.(This is java.net.URl version. Please change accordingly for httpclient)

GZIPInputStream gs = new GZIPInputStream(connection.getInputStream());

    BufferedReader in = new BufferedReader(new InputStreamReader(gs));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();

You should render the response as UTF-8.

And your second question is the Jackson library. It can conver json objects into Java objects.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top