sitelink1  
sitelink2  
sitelink3  

- 테스트 성공 코드

- 개발환경 : Android Studio 3.2.1, API27(Android 8.1 Oreo), Eclipse Neon.3 Release (4.6.3), jdk1.8.0_92, Tomcat 9.0

 

AndroidManifest.xml 

<!-- 네트워크 사용에 대한 퍼미션 -->

<uses-permission android:name="android.permission.INTERNET" />

 

 

Android

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        HttpUtil data_transfer = new HttpUtil();

        JSONObject json_dataTransfer = new JSONObject();

        try

        {

            json_dataTransfer.put("HttpUtil", textView.getText());

            String json_string = json_dataTransfer.toString();

            String url = "http://[your domain]/[your web app]";

            data_transfer.execute(url, json_string);

        }

        catch (JSONException e)

        {

            e.printStackTrace();

        }

    }

 

    public class HttpUtil extends AsyncTask<String, Void, Void> {

 

        String res_json;

 

        @Override

        public Void doInBackground(String... params) {

            HttpURLConnection conn = null;

            try {

                conn = (HttpURLConnection) ((new URL(params[0]).openConnection()));

                conn.setReadTimeout(10000);

                conn.setConnectTimeout(15000);

                conn.setRequestMethod("POST");

                conn.setDoInput(true); // InputStream으로 서버로 부터 응답을 받겠다는 옵션.

                conn.setDoOutput(true); // OutputStream으로 POST 데이터를 넘겨주겠다는 옵션.

                conn.setRequestProperty("Accept-Charset", "UTF-8"); // Accept-Charset 설정.

                conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");

                conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

 

                //Write

                OutputStream os = conn.getOutputStream();

                os.write( params[1].getBytes("UTF-8") );

                os.flush();

                os.close();

 

                //Read

                BufferedReader br = null;

                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                    br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                } else {

                    br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));

                }

 

                String line;

                StringBuffer response = new StringBuffer();

                while((line = br.readLine()) != null) {

                    response.append(line);

                    response.append('\r');

                }

                br.close();

                this.res_json = response.toString();

                //System.out.println(this.res_json);

            } catch (Exception e) {

                e.printStackTrace();

            }

            return null;

        }

 

        @Override

        protected void onPostExecute(Void aVoid) {

            super.onPostExecute(aVoid);

            MainActivity.serverRes.setText(this.res_json); //serverRes는 TextView로써 MainActivity Class에서 public static으로 선언되었고 onCreate에서 가져온다

        }

    }

 

 

Servlet

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));

        String json = "";

        if(br != null){

            json = br.readLine();

        }

        if (json.length() > 0)

            System.out.println("--"+json);

 

        JSONObject resJo = new JSONObject();

        resJo.put("RTN_MSG", "응답데이터입니다");

        this.printJSON(res, resJo.toJSONString());

    }

 

    private void printJSON(HttpServletResponse res, String jsonStr) {

        if (jsonStr != null) {

            res.setCharacterEncoding("UTF-8");

            res.setContentType("application/json");

            res.setHeader("Cache-Control", "no-cache");

            PrintWriter out;

            try {

                out = res.getWriter();

                out.print(jsonStr);

                out.flush();

                out.close();

            } catch (Exception e) {

                e.printStackTrace();

                System.out.println(e);

            }

        }

    }

번호 제목 글쓴이 날짜 조회 수
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
123 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
» [성공샘플] 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