如何从URL打印数据?

时间:2016-04-03 13:21:01

标签: java json urlconnection

我正在尝试在控制台上打印以下URL的内容,但它不会打印任何内容: LINK

请在下面找到我正在使用的代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;



public class CrunchifyCallUrlAndGetResponse {

    public static void main(String[] args) {
        System.out.println("\nOutput: \n" + callURL("http://en.wikipedia.org/w/api.php?format=json&action=query&titles=SMALL&prop=revisions&rvprop=content"));
    }

    public static String callURL(String myURL) {
        System.out.println("Requeted URL:" + myURL);
        StringBuilder sb = new StringBuilder();
        URLConnection urlConn = null;
        InputStreamReader in = null;
        try {
            URL url = new URL(myURL);
            urlConn = url.openConnection();
            if (urlConn != null)
                urlConn.setReadTimeout(60 * 1000);
            if (urlConn != null && urlConn.getInputStream() != null) {
                in = new InputStreamReader(urlConn.getInputStream(),
                        Charset.defaultCharset());
                BufferedReader bufferedReader = new BufferedReader(in);
                if (bufferedReader != null) {
                    int cp;
                    while ((cp = bufferedReader.read()) != -1) {
                        sb.append((char) cp);
                    }
                    bufferedReader.close();
                }
            }
        in.close();
        } catch (Exception e) {
            throw new RuntimeException("Exception while calling URL:"+ myURL, e);
        } 

        return sb.toString();
    }
}

请你在这里帮助我如何从URl获取数据,因为我没有收到任何错误消息,但同时即使网址有数据也没有任何内容被打印出来。

0 个答案:

没有答案