使用Java URL对象

时间:2018-12-18 04:31:56

标签: java rest runtime-error

我正在尝试通过以下链接获取Json文件:https://api.imgflip.com/get_memes

当我将链接添加到Java中的URL对象并尝试使用HttpURLConnection对象进行连接时,我不断收到403错误。有人可以帮我解决我可能缺少的可能吗?

代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String url = "https://api.imgflip.com/get_memes";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

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

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

        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.toString());
    }

}

错误:

Sending 'GET' request to URL : https://api.imgflip.com/get_memesException in thread "main" 
Response Code : 403
java.io.IOException: Server returned HTTP response code: 403 for URL: https://api.imgflip.com/get_memes
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at Main.main(Main.java:25)
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://api.imgflip.com/get_memes
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at Main.main(Main.java:20)

1 个答案:

答案 0 :(得分:1)

他们的官方网站(https://api.imgflip.com/)说,他们对通话次数有限制。您可能超出了通话数量。