티스토리 뷰

[Android] 안드로이드 네이버 검색 API 연동하기

네이버 검색 API를 연동하여 검색 결과를 출력하는 예제입니다.

실행화면입니다.

검색창에 검색어를 입력하면, 네이버 백과사전의 결과를 출력해주는 새로운 화면을 띄웁니다.

순서는 다음과 같습니다. 1. 오픈 API 이용 신청하기 2. 레이아웃 구성하기 3. manifasts 퍼미션 설정하기 4. MainActivity 구현하기 5. SubActivity 구현하기

1. 오픈 API 이용 신청하기

https://developers.naver.com/products/search/

오픈 API를 이용하기 위해서는 사이트에 접속해서 이용 신청을 해야합니다.

이용신청을 한 뒤 간단한 설정이 필요합니다.

패키지 이름을 설정한 뒤, 안드로이드 프로젝트를 생성합니다.

EmptyActivity로 생성해주세요.

2. 레이아웃 구성하기

연동이 주 목적이므로, 검색어를 입력받을 EditText 하나와 이벤트를 실행할 Button 하나만 생성했습니다.

activity_main.xml

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:gravity="center_horizontal">

android:hint="검색어를 입력해주세요"

android:id="@+id/searchText"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

android:id="@+id/searchBtn"

android:text="검색"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="getNaverSearch"/>

sub_activity.xml

xmlns: app = "http://schemas.android.com/apk/res-auto"

xmlns: tools = "http://schemas.android.com/tools"

android :layout_width= "match_parent"

android :layout_height= "match_parent"

tools :context= ".SubActivity"

android :orientation= "vertical" >

android :text= " 검색결과 "

android :layout_width= "wrap_content"

android :layout_height= "wrap_content" />

android :layout_width= "match_parent"

android :layout_height= "match_parent" >

android :id= "@+id/searchResult2"

android :textSize= "20dp"

android :layout_width= "match_parent"

android :layout_height= "match_parent" />

검색결과가 길 경우 스크롤된 화면으로 볼 수 있도록 ScrollView로 지정했습니다.

3. 퍼미션 설정하기

mainifest > AndroidManifest.xml

package= "com.example.a403_30.apitest" >

android :allowBackup= "true"

android :icon= "@mipmap/ic_launcher"

android :label= "@string/app_name"

android :roundIcon= "@mipmap/ic_launcher_round"

android :supportsRtl= "true"

android :theme= "@style/AppTheme" >

하얀색으로 하이라이트된 줄을 추가해줍니다.

퍼미션 설정을 해주지 않으면 에러가 발생합니다.

4. MainActivity 구현하기

Button btn = (Button) findViewById(R.id. searchBtn ) ;

btn.setOnClickListener( new View.OnClickListener() {

@Override

public void onClick (View v) {

TextView searchText = (TextView) findViewById(R.id. searchText ) ;

//final TextView searchResult = (TextView) findViewById(R.id.searchResult);

keyword = searchText.getText().toString() ;

Intent intent = new Intent(MainActivity. this, SubActivity. class ) ;

intent.putExtra( "keyword" , keyword ) ;

startActivity(intent) ;

//searchResult.setText(str);

}

}) ;

버튼 객체를 생성하여 아이디 값을 받아온 뒤, 클릭했을 때 동작될 이벤트를 구현해줍니다.

"검색" 버튼을 클릭하면 서브 액티비티 화면이 호출되면서, 검색창에 입력된 데이터를 서브 액티비티에 전달합니다.

5. SubActivity 구현하기

Thread thread = new Thread(new Runnable() {

@Override

public void run() {

try {

Intent intent = getIntent();

keyword = intent.getStringExtra("keyword");

str = getNaverSearch(keyword);

runOnUiThread(new Runnable() {

@Override

public void run() {

TextView searchResult2 = (TextView) findViewById(R.id.searchResult2);

searchResult2.setText(str);

}

});

} catch (Exception e) {

e.printStackTrace();

}

}

});thread.start();

intent 값으로 받아온 데이터를 String으로 변환한 뒤, str에 저장해줍니다.

runOnUiThread는 스레드가 실행되면서 UI에 변화를 줄 부분입니다.

다음은 네이버 API와 연동하여 데이터 값을 받아올 함수를 구현한 부분입니다.

맨 처음 API 이용 신청을 한 뒤에 받은 Client ID와 ClientSecret 값이 있습니다.

아래 선언된 변수에 할당받은 값을 넣어줍니다.

public String getNaverSearch(String keyword) {

String clientID = "Client ID 값;

String clientSecret = "Client Secret값";

StringBuffer sb = new StringBuffer();

try {

String text = URLEncoder.encode(keyword, "UTF-8");

String apiURL = "https://openapi.naver.com/v1/search/encyc.xml?query=" + text + "&display=10" + "&start=1";

URL url = new URL(apiURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setRequestProperty("X-Naver-Client-Id", clientID);

conn.setRequestProperty("X-Naver-Client-Secret", clientSecret);

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

XmlPullParser xpp = factory.newPullParser();

String tag;

//inputStream으로부터 xml값 받기

xpp.setInput(new InputStreamReader(conn.getInputStream(), "UTF-8"));

xpp.next();

int eventType = xpp.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {

switch (eventType) {

case XmlPullParser.START_TAG:

tag = xpp.getName(); //태그 이름 얻어오기

if (tag.equals("item")) ; //첫번째 검색 결과

else if (tag.equals("title")) {

sb.append("제목 : ");

xpp.next();

sb.append(xpp.getText().replaceAll("<(/)?([a-zA-Z]*)(\\\\s[a-zA-Z]*=[^>]*)?(\\\\s)*(/)?>", ""));

sb.append("

");

} else if (tag.equals("description")) {

sb.append("내용 : ");

xpp.next();

sb.append(xpp.getText().replaceAll("<(/)?([a-zA-Z]*)(\\\\s[a-zA-Z]*=[^>]*)?(\\\\s)*(/)?>", ""));

sb.append("

");

}

break;

}

eventType = xpp.next();

}

} catch (Exception e) {

return e.toString();

}

return sb.toString();

}

from http://titanic1997.tistory.com/36 by ccl(A)

댓글