2016년 6월 29일 수요일

Android Studio - AsyncTask를 이용한 REST API GET/POST 콜


AsyncTask 관련해서 참조할 만한 사이트가 별로 없어서 만들어 봤다.


GetBear.java

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

/** * AsyncTask를 이용하여 REST GET콜을 통한 JSON을 얻어오는 클래스. */public class GetBear {

    public GetBear() {

    }

    public void getBear(String id){
        // inner class로 구현한 GetTask 객체를 통해 REST API        new GetTask().execute("http://70.12.108.133:8080/api/bears/"+id);
    }

    // AsyncTask inner class로 구현    private class GetTask extends AsyncTask<String, Void, String> {
        @Override        protected String doInBackground(String... params) {
            try{
                return GET(params[0]);
            }catch (IOException e){
                return "Unable to retreive data. URL may be invalid.";
            }
        }

        @Override        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }

    private String GET(String myurl) throws IOException{
        InputStream inputStream = null;
        String returnString = "";

        int length = 500;


        try{
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d("REST GET", "The response is : " + response);
            inputStream = conn.getInputStream();


            // convert inputStream into json            returnString = convertInputStreamToString(inputStream, length);
            JSONObject json = new JSONObject(returnString);

            Log.d("REST GET", "The response is : " + json.toString());
        }catch (Exception e){
            Log.e("REST GET", "Error : "+e.getMessage());
        }finally {
            if(inputStream != null)
                inputStream.close();
        }
        return returnString;
    }

    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[length];
        reader.read(buffer);
        return new String(buffer);
    }
}


PostBear.java

import android.os.AsyncTask;
import android.util.Log;

import com.multicampus.anddbsample.vo.Bear;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/** * AsyncTask를 이용하여 REST POST콜을 통해 JSON을 입력하는 클래스. */public class PostBear {

    private Bear bear;

    public void postBear(Bear bear){
        this.bear = bear;
        new PostTask().execute("http://70.12.108.133:8080/api/bears");
    }

    // AsyncTask inner class로 구현    private class PostTask extends AsyncTask<String, Void, String>{

        @Override        protected String doInBackground(String... params) {
            try{
                return POST(params[0]);
            }catch (IOException e){
                return "Unable to retreive data. URL may be invalid.";
            }
        }
    }

    private String POST(String myurl) throws IOException{
        InputStream inputStream = null;
        String returnString = "";

        JSONObject json = new JSONObject();

        int length = 500;

        try{
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.connect();

            json.accumulate(Bear.NAME, bear.getName());

            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(json.toString());
            writer.flush();
            writer.close();

            int response = conn.getResponseCode();
            Log.d("REST POST", "The response is : " + response);
        }catch(Exception e){
            Log.e("REST POST", "Error : " + e.getMessage());
        }finally{
            if(inputStream != null)
                inputStream.close();
        }
        return returnString;
    }
}


MainActivity.java

private void setDefaultEvent(){
    btnSubmit.setOnClickListener(new View.OnClickListener(){

        @Override        public void onClick(View v) {

            getBear.getBear("57721c41aa42685017000001");
        }
    });

    btnList.setOnClickListener(new View.OnClickListener(){

        @Override        public void onClick(View v) {
            postBear.postBear(new Bear("AI-BaoBao"));
        }
    });
}



아래 기트허브 참조
https://github.com/GlennHKim/MessengerUsingAsyncTask

댓글 없음:

댓글 쓰기