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);

            }

        }

    }

번호 제목 글쓴이 날짜 조회 수
68 TTS 를 위한 스마트폰 설정 및 TTS 샘플 file 황제낙엽 2019.02.16 460
67 Creating swipe views with tabs file 황제낙엽 2019.02.10 102
66 [번역] 안드로이드 ViewPager 를 이용한 수평 화면 전환 file 황제낙엽 2019.02.09 71
65 동적 레이아웃 생성과 자동 줄바꿈 구현 file 황제낙엽 2018.12.26 311
64 qemu-system-~.exe 의 작동이 중지되었습니다 file 황제낙엽 2018.11.27 55
63 Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'. file 황제낙엽 2018.11.27 59
62 Error:Minimum supported Gradle version is 4.1. 황제낙엽 2018.11.27 84
61 No toolchains found in the NDK toolchains folder for ABI 황제낙엽 2018.11.27 33
» [성공샘플] HttpURLConnection 을 이용하여 JSON 데이터 보내기 예제 황제낙엽 2018.11.10 649
59 [Android] 네이버 음성합성(TTS) API 사용해 보기 file 황제낙엽 2018.11.01 167
58 [Android] TTS (Text To Speech) API 샘플 코드 file 황제낙엽 2018.11.01 128
57 Google Cloud API 설정법 file 황제낙엽 2018.11.01 39
56 AsyncTask 사용하기 황제낙엽 2018.10.29 36
55 Volley 소개 및 관련 링크 황제낙엽 2018.10.29 63
54 AsyncTask 를 이용한 HttpURLConnection 사용법 [1] 황제낙엽 2018.10.20 33
53 HttpURLConnection 을 이용하여 JSON 데이터 보내기 예제 [1] file 황제낙엽 2018.10.20 102
52 STT 학습 링크 모음 (sample link) 황제낙엽 2018.10.11 552
51 코틀린(Kotlin) 학습용 링크 모음 황제낙엽 2018.10.11 64
50 저장소 파일 불러올 때 권한 요청 설정 file 황제낙엽 2018.08.21 55
49 안드로이드 파일시스템에 파일 생성하여 데이터 저장, 불러오기 예제 황제낙엽 2018.08.21 58