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

번호 제목 글쓴이 날짜 조회 수
28 Android Studio for beginners, Part 3: Build and run the app file 황제낙엽 2018.02.02 81
27 Android Studio for beginners, Part 2: Explore and code the app(2) file 황제낙엽 2018.02.02 17
26 Android Studio for beginners, Part 2: Explore and code the app(1) file 황제낙엽 2018.02.02 36
25 Android Studio for beginners, Part 1: Installation and setup file 황제낙엽 2018.02.02 23
24 SDK와 NDK, 그리고 PDK 황제낙엽 2018.01.30 69
23 Error:Execution failed for task ':app:lintVitalRelease'. 황제낙엽 2018.01.29 783
22 Error:The number of method references in a .dex file cannot exceed 64K. 황제낙엽 2018.01.29 70
21 30일 기한 Google Play 개발자 약관 위반 알림 황제낙엽 2018.01.21 125
20 애니메이션 샘플 예제들 file 황제낙엽 2018.01.08 186
19 ConstraintLayout으로 숫자패드 레이아웃을 file 황제낙엽 2017.11.09 144
18 RecyclerView란? (RecyclerView와 ListView 차이) file 황제낙엽 2017.09.11 153
17 Android - Actionbar에 tab을 추가하고 스와이프 동작으로 화면 전환 구현( ViewPager와 FragmentPagerAdapter 사용) file 황제낙엽 2017.09.11 308
» HTTP 프로토콜을 이용한 Json Post 보내고 받기 file 황제낙엽 2017.08.03 816
15 HttpURLConnection 에서 세션 유지하기(쿠키 사용) 황제낙엽 2017.08.03 661
14 Android HttpURLConnection클래스로 POST 요청하기 황제낙엽 2017.08.01 65
13 Android’s HTTP Clients & Apache HTTP Client 어느것이 성능이 더 좋을까? 황제낙엽 2017.07.31 157
12 프로젝트의 AndroidManifest.xml 파일의 내용 file 황제낙엽 2017.07.25 52
11 구글의 안드로이드 개발자들이 만든 애플리케이션 모음 (Apps for Android ) file 황제낙엽 2017.07.25 56
10 크롬에서 디바이스(스마트폰) 연결 정보 확인 황제낙엽 2017.03.28 215
9 JNI 사용시 Android.mk와 Application.mk에 대해서 황제낙엽 2017.03.28 28