2017-09-21 5 views
-1

私はアンドロイドでプログラミングには新しく、私はアンドロイドアプリのウェブサイトhttps://api.clashofclans.com/v1/clansからjsonデータを取得したかったのです。 json形式でデータを要求する方法 curl -X GET --header 'Accept:application/json' --header "authorization:Bearer" 'https://api.clashofclans.com/v1/clans' 私は、組み合わせとオープンネットワーク接続でAPIキーを追加する方法を知らない。前もって感謝します。私のコードは、APIキーがIPアドレスに基づいて 間違っているところuは私を伝えることができ、:Android cUrl api

urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.setReadTimeout(10000 /* milliseconds */); 
     urlConnection.setConnectTimeout(15000 /* milliseconds */); 
     urlConnection.setRequestMethod("GET"); 
     urlConnection.addRequestProperty("Accept","application/json"); 
     urlConnection.addRequestProperty("authorization","my api-key here"); 
     urlConnection.connect(); 

     // If the request was successful (response code 200), 
     // then read the input stream and parse the response. 
     if (urlConnection.getResponseCode() == 200) { 
      inputStream = urlConnection.getInputStream(); 
      jsonResponse = readFromStream(inputStream); 
     } else { 
      Log.e(LOG_TAG, "Error response code: " + 
     urlConnection.getResponseCode()); 
     } 

iは、「403エラー応答コード」を取得しています。

+0

結論はありましたか?私は同じ問題を抱えています:カールは許可でうまく動作しますが、http APIは403を返します。なぜ、あなたは質問で-1を得ましたか? – narb

+0

私は-1については知らないが、いくつかの変更の後で、以下の解決策が機能した。 – rohit

答えて

1

私はそれを文字列として返すところこれが私のメソッドに送信するイム:

public void getJson() { 
    String json = getJSONFromURLConnection("https://api.clashofclans.com/v1/clans?name=illuminati"); 
    if (json != null) { 
     Log.i("JSON", json.toString()); 
    } 
} 

ここではすべての情報取得:

private String getJSONFromURLConnection(String urlString) { 
    BufferedReader reader = null; 

    try { 
     URL url = new URL(urlString); 
     urlConnection = (HttpURLConnection) url.openConnection(); 

     String apikey = YOUR_KEY; 
     urlConnection.setRequestMethod("GET"); 
     urlConnection.addRequestProperty("Authorization", "Bearer " + apikey); 
     urlConnection.setRequestProperty("Accept", "application/json"); 

     if (urlConnection.getResponseCode() == 200) { 
      InputStream stream = urlConnection.getInputStream(); 

      reader = new BufferedReader(new InputStreamReader(stream)); 

      StringBuffer buffer = new StringBuffer(); 

      String line; 

      while ((line = reader.readLine()) != null) { 
       buffer.append(line); 
      } 

      return buffer.toString(); 
     } else { 
      Log.e("Error", "Error response code: " + 
        urlConnection.getResponseCode()); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (urlConnection != null) 
      urlConnection.disconnect(); 
    } 
    return null; 
} 

を作成してテストしたが、私の作品は、あなたが結果を得る願っていますあなたが必要です。

+0

承認のためのAPIキーはどこに追加しますか? – rohit

+0

の "connection"では、次のようなプロパティを設定することができます:connection.addRequestProperty( "x-api-key"、apiKey); –

+0

私は自分のコードを編集していますが、私はどこが間違っているか教えてくれます。 – rohit