2017-08-21 5 views
0

を返し、私はここでネイティブJavaJavaはanapioficeandfireからURLを読み込むには403

https://anapioficeandfire.com/api/characters/583からJSONを取得するコードは次のとおりです。

import java.net.*; 
import java.io.*; 

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

     URL oracle = new URL("https://anapioficeandfire.com/api/characters/583"); 
     BufferedReader in = new BufferedReader(
       new InputStreamReader(oracle.openStream())); 

     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine); 
     in.close(); 
    } 
} 

私は何を取得すると、このエラーです:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://anapioficeandfire.com/api/characters/583 
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876) 
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474) 
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) 
    at java.net.URL.openStream(URL.java:1045) 
    at sprint2.fireandice.Main.main(Main.java:17) 

このコードはexample.com、google.comなどで動作します...

+0

https://stackoverflow.com/questions/13670692/403-forbidden-with-java-but-not-web-browserでの答えは、それは入力しなくても働いていた、 –

答えて

2

問題はです。サーバーはこのConnectionを拒否し、403 Forbiddenを送信します。ユーザーエージェントを設定することで、サーバーを "欺く"ことができ、通常のブラウザのように動作します。

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

    URL oracle = new URL("https://anapioficeandfire.com/api/characters/583"); 
    HttpURLConnection httpcon = (HttpURLConnection) oracle.openConnection(); 
    httpcon.addRequestProperty("User-Agent", "Mozilla/4.0"); 

    BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); 

    String inputLine; 
    while ((inputLine = in.readLine()) != null) 
     System.out.println(inputLine); 
    in.close(); 
} 
+1

Thxをたくさんあなたを助ける必要があります.openConnection()を(HttpURLConnection)に設定します。 URLConnection myUrlConnection = myUrl.openConnection(); myUrlConnection.addRequestProperty( "User-Agent"、 "Mozilla/4.0"); – Demaunt

+0

恐ろしい答え、それは私が何か間違っていると思っているサーバーと関係があると分かっていました。私はちょうど何を探すべきか分からなかった。 – LatheElHafy

関連する問題