以下是我的Java代码,用于从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());
}
}
我的控制台里有很多追随者。
Testing 1 - Send Http GET request
Response Code : 200
�
我试着将内容写入文件,结果就像
� 0 0 0 0 0 0�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 0�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 0l�a� �S���B��8�q�P���h� �H<�ݼ��g�^|.����y���G/���c� 0u2a���LQ�����_ņ=ů7w�A?�Ĵ>�$%X� �͇f��Ib�%AA�_8���T����(C�����S�,�Y��A�nYu<K��$��1y��( 0Rg�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 0$όu� 'J��+�,KU4fs[5e������vh�� h��K+��4�T>�!*,���JH2.��>$�rC�)�9�!�3k��eee�O��2�`�N�ݯ]���~^ɦ}@��g��>rM��LT�Ѡ 0�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�{ 0PR�l>