본문 바로가기

카테고리 없음

다음API(이미지 검색)

DaumAPI.java

package com.example.ex18;
import  java.net.*;
import java.io.*;
public class DaumAPI {
    public static String main(String apiURL,String query) {

        try {
            String text = URLEncoder.encode(query, "UTF-8");



            apiURL += "?query=" + text;

            apiURL += "&size=10";

            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");
            //Authorization
            con.setRequestProperty("Authorization"," KakaoAK 6baa3500ff42695b48d705aa87132cb3");

            int responseCode = con.getResponseCode();
            BufferedReader br;
            if(responseCode==200) { // 정상 호출
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else {  // 에러 발생
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
            System.out.println(response.toString());
            return response.toString();
        } catch (Exception e) {
            System.out.println(e);
            return e.toString();
        }
    }
}


ImageActivity.java

package com.example.ex18;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class ImageActivity extends AppCompatActivity {

    String apiURL="https://dapi.kakao.com/v2/search/image";
    String query="설현";


    ArrayList<ImageVO> array=new ArrayList<ImageVO>();

        RecyclerView list;
    ImageAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list=findViewById(R.id.list);
        LinearLayoutManager manager=new LinearLayoutManager(this);
        list.setLayoutManager(manager);


        getSupportActionBar().setTitle("이미지 검색");

        new ImageThread().execute();

        final EditText edtsearch=findViewById(R.id.edtsearch);
        edtsearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                query=edtsearch.getText().toString();

                array.clear();
                new ImageThread().execute();
                return false;
            }
        });
    }
    //BackThread
    class ImageThread extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... strings) {
            return DaumAPI.main(apiURL,query);
        }

        @Override
        protected void onPostExecute(String s) {
            System.out.println("결과:" + s);
            try {
                JSONArray jArray=new JSONObject(s).getJSONArray("documents");
                for(int i=0; i<jArray.length(); i++){
                    JSONObject obj=jArray.getJSONObject(i);
                    ImageVO vo=new ImageVO();
                    vo.setImage(obj.getString("image_url"));
                    vo.setSite(obj.getString("display_sitename"));
                    vo.setDate(obj.getString("datetime"));
                    vo.setThumnail(obj.getString("thumbnail_url"));
                    array.add(vo);
                    System.out.println(vo.toString());

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            adapter=new ImageAdapter(array,ImageActivity.this);
            list.setAdapter(adapter);
            super.onPostExecute(s);
        }
    }
}


ImageVO.java

package com.example.ex18;

public class ImageVO {
    private String image;
    private String thumnail;
    private String site;
    private String date;

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getThumnail() {
        return thumnail;
    }

    public void setThumnail(String thumnail) {
        this.thumnail = thumnail;
    }

    public String getSite() {
        return site;
    }

    public void setSite(String site) {
        this.site = site;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("ImageVO{");
        sb.append("image='").append(image).append('\'');
        sb.append(", thumnail='").append(thumnail).append('\'');
        sb.append(", site='").append(site).append('\'');
        sb.append(", date='").append(date).append('\'');
        sb.append('}');
        return sb.toString();
    }
}


activity_image.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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=".ImageActivity">

</androidx.constraintlayout.widget.ConstraintLayout>


item_image.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#4CAF50"
    android:padding="10sp">
    <ImageView
        android:layout_width="50sp"
        android:layout_height="50sp"
        android:id="@+id/image"
        android:layout_marginRight="10sp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="출저명"
        android:textSize="15sp"
        android:layout_toRightOf="@id/image"
        android:layout_marginTop="10sp"
        android:id="@+id/txtsite"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="작성일"
        android:textSize="13sp"
        android:layout_toRightOf="@id/image"
        android:layout_below="@id/txtsite"
        android:layout_marginTop="10sp"
        android:id="@+id/txtdate"
        android:layout_marginLeft="5sp"/>
</RelativeLayout>


activity_big_image.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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=".BigImageActivity"
    android:orientation="vertical"
    android:padding="10sp">
    <TextView
        android:id="@+id/txtsite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="사이트명"
        android:textSize="30sp"
        android:layout_gravity="center"
        android:layout_marginBottom="20sp"/>
    <ImageView
        android:id="@+id/image"
        android:layout_gravity="center"
        android:layout_width="350sp"
        android:layout_height="350sp"/>
</LinearLayout>


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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=".MainActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtsearch" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_search"
        android:layout_alignParentRight="true"
        android:layout_marginTop="3sp"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/edtsearch"
        android:layout_marginTop="-2dp"
        android:padding="10sp" />
</RelativeLayout>