728x90

https://newsapi.org/v2/top-headlines?country=kr&category=science&apiKey=a30a7298cf91404494ce049edc3d0e5a 에 있는 자료를 안드로이드에서 가져와서 Recyclerview 로 처리하는 걸 하고 싶은데 안된다는 내용이다.


안드로이드 앱에서는 아래와 같은 에러가 발생한다.


분명히 Web에서 직접 URL을 입력하면 결과를 출력하고 있다.

직접 API 를 신청하는 것도 해봤다.




해결하는 방법은 PHP CURL 을 이용하면 된다.

<?php
// PHP cURL 모듈은 다양한 종류의 프로토콜을 사용하여 서버와 통신할 수 있도록 도와주는 모듈로 외부 사이트의 정보를 취득할 수 있다.
// 서버에 PHP CURL 모듈이 설치되어 있어야 한다.
$url = "https://newsapi.org/v2/top-headlines?country=kr&category=science&apiKey=a30a7298cf91404494ce049edc3d0e5a";
// curl이 설치 되었는지 확인
if (function_exists('curl_init')) {
    
    $ch = curl_init(); // curl 리소스 초기화
    curl_setopt($ch, CURLOPT_URL, $url); // url 설정    
    curl_setopt($ch, CURLOPT_HEADER, 0); // 헤더는 제외하고 content 만 받음    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 응답 값을 브라우저에 표시하지 말고 값을 리턴

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_VERBOSE, true);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //true로 설정시 일부 https 사이트는 안 열림
    curl_setopt($ch, CURLOPT_SSLVERSION,1); //ssl 셋팅

    $content = curl_exec($ch);    
    curl_close($ch); // 리소스 해제

    $R = json_decode($content,TRUE); // JSON to Array
    echo json_encode($R); // JSON

} else {
    // curl 라이브러리가 설치 되지 않음. 다른 방법 알아볼 것
    echo "This website not installed PHP's curl function.";
}
?>


서버에 올려진 이 URL 을 호출하면 원하는 News API 자료를 가져올 수 있다.

앱 출력 결과




블로그 이미지

Link2Me

,