2017-09-21 4 views
-1

나는 안드로이드 프로그래밍에 초보자이며, 안드로이드 앱에있는 https://api.clashofclans.com/v1/clans 웹 사이트에서 json 데이터를 얻고 싶었습니다. json 형식으로 데이터를 요청하는 방법 curl -X GET - 헤더 '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을 반환한다. BTW, 왜 질문에 -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