sitelink1 http://naver.me/5B909Oa6 
sitelink2  
sitelink3  

전 포스트에서 protobuf를 이용해 TCP/IP 통신을 해봤다면, 이번에는 간단하게 웹서버와 안드로이드와 통신으로 HTTP를 이용해서 텍스트 방식의 Json 데이타를 주고 받는 방법을 테스트 해봤다.

그런데 이방법을 알아보면서 안드로이드 6.0부터 Apache HTTP API는 지원안한다고 한다. 기존 HTTP를 이용한 통신방법은 거의다 이걸 이용한 예제인데 앞으로는 HttpURLConnection 클래스를 이용하라고 하는데, 이유는 이게 더 효율적이라고 한다. 아래 링크에 자세한 내용이 나온다.

https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client

Android 6.0 Changes | Android Developers

developer.android.com

 

물론 기존 코드를 이용하는 방법이 있긴 한데 기왕이면 안드로이드에서 지원하는 방식을 사용해야 앞으로도 기존코드를 지원하기위해 수작업이 필요없고 효율도 좋다고하니 HttpURLConnection 클래스를 이용하는 방법으르 통신 테스트를 진행했다.

기존 코드를 사용할 수 있도록 설정하는 방법은 아래 링크에 나온다.

http://stackoverflow.com/questions/30856785/how-to-add-apache-http-api-legacy-as-compile-time-dependency-to-build-grade-fo/32108524#32108524

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

As mentioned here, Android M will not support the Apache HTTP API. The docs state to: use the HttpURLConnection class instead. or To continue using the Apache HTTP APIs, you must first

stackoverflow.com

 

Json이 데이타만 있지만 텍스트라 통신내용을 캡쳐하면 무슨 데이타인지 대충알 수 있는데 Post 방식으로 보내면 보안적으로 좀 낫지 않을까 싶다. 

http://hmkcode.com/android-send-json-data-to-server/ 

Android | Send “POST” JSON Data to Server | HMKCode

hmkcode.com

위 링크에 Apache HTTP API을 이용한 Json을 이용한 Post 방식의 샘플코드가 잘되어 있어서 이걸 이용하여 HttpURLConnection을 사용한 방식으로 바꿔봤다. Json을 Post로 보내려면 웹서버가 있어야 하는데 위에 링크에서 웹서비스를 제공하고 있어 바로 테스트가 가능했다. 

http://hmkcode.appspot.com/jsonservlet ) 

 

HttpURLConnection 클래스를 이용한 Post 방식은 간단했다. 아래에 통신코드만 추가하고 나머지 전체 코드는 첨부파일로 올려놓았다. ( Android Studio v2.1.1 기준 )

 

import java.net.HttpURLConnection;

import java.net.URL;

 

public static String POST(String url, Person person){

        InputStream is = null;

        String result = "";

        try {

            URL urlCon = new URL(url);

            HttpURLConnection httpCon = (HttpURLConnection)urlCon.openConnection();

 

            String json = "";

 

            // build jsonObject

            JSONObject jsonObject = new JSONObject();

            jsonObject.accumulate("name", person.getName());

            jsonObject.accumulate("country", person.getCountry());

            jsonObject.accumulate("twitter", person.getTwitter());

 

            // convert JSONObject to JSON to String

            json = jsonObject.toString();

 

            // ** Alternative way to convert Person object to JSON string usin Jackson Lib

            // ObjectMapper mapper = new ObjectMapper();

            // json = mapper.writeValueAsString(person);

 

            // Set some headers to inform server about the type of the content

            httpCon.setRequestProperty("Accept", "application/json");

            httpCon.setRequestProperty("Content-type", "application/json");

 

            // OutputStream으로 POST 데이터를 넘겨주겠다는 옵션.

            httpCon.setDoOutput(true);

            // InputStream으로 서버로 부터 응답을 받겠다는 옵션.

            httpCon.setDoInput(true);

 

            OutputStream os = httpCon.getOutputStream();

            os.write(json.getBytes("euc-kr"));

            os.flush();

            // receive response as inputStream

            try {

                is = httpCon.getInputStream();

                // convert inputstream to string

                if(is != null)

                    result = convertInputStreamToString(is);

                else

                    result = "Did not work!";

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            finally {

                httpCon.disconnect();

            }

        }

        catch (IOException e) {

            e.printStackTrace();

        }

        catch (Exception e) {

            Log.d("InputStream", e.getLocalizedMessage());

        }

 

        return result;

 

    }

 

자기 정보를 입력하여 Post버튼을 누르면 Json 포맷으로 데이타를 보내고 서버에서 자기정보가 마지막에 추가된 Json 데이타 전체를 보내준다. 실행결과 화면은 다음과 같다.

 

postjson.png

 

 

 

#참고사이트

http://hmkcode.com/android-send-json-data-to-server/

https://www.learn2crack.com/2013/10/android-asynctask-json-parsing-example.html

http://arabiannight.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9CAndroid-HttpUrlConnection-Request-%EC%84%A4%EB%AA%85-%EB%B0%8F-%EC%84%A4%EC%A0%95-%ED%95%98%EA%B8%B0-header-get-post-body%EB%93%B1

번호 제목 글쓴이 날짜 조회 수
128 단말기 고유값 구하는 방법들 황제낙엽 2019.03.03 11739
127 뷰 캡처하여 이미지 파일로 저장하기(화면 캡처)-04 file 황제낙엽 2018.08.12 1711
126 고유 식별자의 모범 사례 (Android Developers) 황제낙엽 2019.03.03 1106
125 Emulator: audio: Failed to create voice `adc' 황제낙엽 2018.08.06 1007
124 뷰 캡처하여 이미지 파일로 저장하기(화면 캡처)-06 file 황제낙엽 2018.08.19 991
» HTTP 프로토콜을 이용한 Json Post 보내고 받기 file 황제낙엽 2017.08.03 816
122 Error:Execution failed for task ':app:lintVitalRelease'. 황제낙엽 2018.01.29 783
121 파일 입출력(내장 메모리, 외장메모리) 황제낙엽 2018.08.19 720
120 HttpURLConnection 에서 세션 유지하기(쿠키 사용) 황제낙엽 2017.08.03 661
119 [성공샘플] HttpURLConnection 을 이용하여 JSON 데이터 보내기 예제 황제낙엽 2018.11.10 649
118 Image to byte Array (바로 사용가능한 JPEG 파일) 황제낙엽 2018.07.24 612
117 STT 학습 링크 모음 (sample link) 황제낙엽 2018.10.11 552
116 ABI 관리 황제낙엽 2017.03.28 535
115 TTS 를 위한 스마트폰 설정 및 TTS 샘플 file 황제낙엽 2019.02.16 460
114 안드로이드 스튜디오(Android Studio) 최적화 file 황제낙엽 2018.02.07 433
113 android.webkit.CookieManager 를 이용한 웹뷰와의 세션 공유 황제낙엽 2019.04.26 322
112 동적 레이아웃 생성과 자동 줄바꿈 구현 file 황제낙엽 2018.12.26 311
111 Android - Actionbar에 tab을 추가하고 스와이프 동작으로 화면 전환 구현( ViewPager와 FragmentPagerAdapter 사용) file 황제낙엽 2017.09.11 308
110 안드로이드 두지점(위도,경도) 사이의 거리 file 황제낙엽 2017.01.25 257
109 안드로이드 기기 식별 방법 - UUID(Universally unique identifier) 황제낙엽 2019.03.03 234