BLOG main image
분류 전체보기 (28)
루비 (3)
glassfish (1)
건아 (1)
RFC 한글 (0)
TIP (5)
VCS(Version Control System) (3)
perl (4)
java (2)
android (0)
javascript&Jquery (2)
기술문서 번역 (0)
사이베이스(ASE) (3)
용어 (2)
GAE&GCP (0)
사는 이야기 (1)
Visitors up to today!
Today hit, Yesterday hit
daisy rss
tistory 티스토리 가입하기!
2014. 5. 29. 11:32

보통 HttpClient로 작업을 해 왔는데 이번에는 HttpUrlConnection으로 작업을 해야했다. 
(특정 호스팅 상황에서 HttpClient가 지원되지 않는 상황이 발생)

아래의 소스는 SMS 발송서버로 데이타를 던지는 샘플이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@SuppressWarnings("serial")
public class SENDSMSServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String send_num="112";
        String receive_num="01012345678,01009876543";
        String contents = "다건 SMS 테스트중입니다. ";
        System.out.println("values " + values);
//        boolean sms = httpConnForSMS(values);
        boolean sms = httpConnForSMS(send_num,receive_num,contents);
        System.out.println("SEND RESULT " + sms);
    }
    
public static boolean httpConnForSMS(String sendNum, String receiveNum, String contents) {
        
        /**
         * params[0] : sender
         * params[1] : receiver
         * params[2] : contents
         */
        
        boolean result = false;
        try {
            URL url = new URL("http://xxxxxxxxx/_include/send_sms.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 서버로부터 메세지를 받을 수 있도록 설정. (기본값 : true)
            connection.setDoOutput(true);
            // 헤더 설정
            // 메소드 설정 (기본값 : GET)
            connection.setRequestMethod("POST");
            // 서버로 메세지를 보낼 수 있도록 설정.
            connection.setDoOutput(true);
                       
            // 파라미터 전송.
            StringBuilder sb = new StringBuilder();
            sb.append("send_num=")
              .append(URLEncoder.encode(sendNum, "UTF-8"))
              .append("&receive_nums=")
              .append(URLEncoder.encode(receiveNum, "UTF-8"))
              .append("&sms_con=")
              .append(URLEncoder.encode(contents, "UTF-8"));
            
            OutputStream writer = connection.getOutputStream();
            writer.write(sb.toString().getBytes("UTF-8"));
            writer.flush();
            writer.close();
            
            //////////////////////////////////////////////////
            ////////////////// If GET Method  ////////////////            
            //String urlStrings = "http://......";
            //urlStrings += "&sender=";
            //HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //////////////////////////////////////////////////
            int responseCode = connection.getResponseCode();   
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 발송성공..
                result = true;
            } else {
                // 발송실패..
            }
        } catch (MalformedURLException e) {
            // ...
            e.printStackTrace();
        } catch (IOException e) {
            // ...
            e.printStackTrace();
        } finally {
            
        }
 
        return result;
    }
}


'java' 카테고리의 다른 글

Mysql에서 Oracel로 쿼리 변경시 limit  (0) 2013.12.26
2014. 5. 29. 11:23

초기 jqgrid에는 아무 값도 셋팅하지 않기 위해 url 설정이 없다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
jQuery("#grid").jqGrid({
        datatype: "json", 
        //가져온 데이터를 읽을 때 사용
        jsonReader: {
             root: "rows",
             page: "page",
             total: "total",
             records: "records",
             repeatitems: true,
             cell: "cell",
             id: "id"
        },                                                     //json형태로 데이터 받음. 
        height: 550,
        autowidth: true,
        colNames:['예약일시','휴양소명','휴양소id','예약번호','객실명','객실id','지망','사번','성명','연락처','확정'],    //컬럼 구성요소
        colModel:[  
            //각 컬럼에 바인딩될 json 키값
            {name:'stay_start_date',index:'stay_start_date', width:100, align: 'center', sortable:true, formatter:'srcformat' },
            {name:'rnrc_name',index:'rnrc_name', width:100, align: 'center', sortable:true },
            {name:'rnrc_id',index:'rnrc_id', width:100, align: 'center', sortable:true, hidden:true },
            {name:'reserved_id',index:'reserved_id', width:100, align: 'center', sortable:true, hidden:true },
            {name:'room_name',index:'room_name', width:100, align: 'center', sortable:true },
            {name:'room_id',index:'room_id', width:100, align: 'center', sortable:true, hidden:true  },
            {name:'ranking',index:'ranking', width:100, align: 'center', sortable:true },            
            {name:'emp_no',index:'emp_no', width:100, align: 'center', sortable:true },           
            {name:'name',index:'name', width:100, align: 'center', sortable:true },
            {name:'phone_no',index:'phone_no', width:100, align: 'center', sortable:false },
            {name:'fix_flag',index:'fix_flag', width:100, align: 'center', sortable:true, formatter:formatOpt1}
        ],    
        rowNum: 1000,                             //기본 row 수 request 시 rows로 받으면 됨.
        //rowList:[5,10,30],                   //rowNum 수 변경 
        rowTotal: 2000,                  
        rownumbers : true,                      //리스트 순번
        autoencode: true,
        //viewrecords: true,                      //하단 레코드 수 표시 유무
        emptyrecords : '결과가 없습니다.',      //row가 없을 경우 출력 할 text
        multiselect: true,                     //전체선택 체크박스 유무, 테이블에서 row 체크를 멀티로 할 수 있는 옵션.
        gridview: true,
        mtype: "GET", 
        loadtext: "데이타 로딩중..... 잠시 기다려 주십시오.",
        caption: "예약신청자 일람",  
        sortable: true,
        loadonce: false,
        onPaging: function (pgButton) {
            // 페이징 확인용 
            var newUserValue = $('input.ui-pg-input', "#pg_pagerId").val();
            var newValue = 0;
            var currentValue = $("#grid").getGridParam('page');
            if (pgButton.indexOf("next") >= 0)
                newValue = ++currentValue;
            else if (pgButton.indexOf("prev") >= 0)
                newValue = --currentValue;
            else if (pgButton.indexOf("last") >= 0)
                newValue = $("#grid").getGridParam('lastpage');
            else if (pgButton.indexOf("first") >= 0)
                newValue = 1;
            else if (pgButton.indexOf("user") >= 0)
                newValue = newUserValue;
            // 페이징 확인용 끝    
            
            /* 
            * searchBtn 과 페이징 버튼을 구분하기 위해서 
            * 페이징 버튼을 눌렀을 때는 searchBtn이 없는 url을 그리드에 셋팅함.
            **/
            $("#grid").jqGrid('setGridParam', {url:"/rnrc_a03/rnrcGridInfoList.do?from="+ $('#from').val()
                                                             + "&to="+ $('#to').val() 
                                                             + "&rnrc_id=" + $('#selectPension').val()
                                                             + "&room_id=" + $('#selectRoom').val()
                                                             + "&emp_no=" + $('#selectEmp').val()
                                                             + "&fix_flag=" + $('#fix_flag').val()
                                                             })
            
        },
        sortname: 'stay_start_date',
        sortorder: 'asc',
        //toppager: true,                       //상단에 페이저 추가        
        //pagerpos: 'center',                     //페이징 위치
        //pgbuttons: true,                        //페이징 버튼 유무
        //pginput: true,                          //페이징 인풋입력 유무
        pager : '#gridpager',
        //recordtext:"총 {2} 건 중 {0} 건 부터 {1}건 까지의 데이타입니다."
    });



조회 버튼 등의 이벤트 발생시 url을 지정해 주고 리로드 한다.


1
2
3
4
5
6
7
8
$("#grid").jqGrid('setGridParam', {url:"/rnrc_a03/rnrcGridInfoList.do?from="+ $('#from').val()
                                                             + "&to="+ $('#to').val() 
                                                             + "&rnrc_id=" + $('#selectPension').val()
                                                             + "&room_id=" + $('#selectRoom').val()
                                                             + "&emp_no=" + $('#selectEmp').val()
                                                             + "&fix_flag=" + $('#fix_flag').val()
                                                             + "&searchStatus=" + id                                                             
                                                             }).trigger("reloadGrid");



특정 이벤트시에 에러를 반환하기 위해서 loaderror 옵션을 추가 하였으나 계속해서 초기 그리드 로딩시 (url이 없어도 로딩을 한다. 아마 "/" 를 참조하는 것 같았다. index.jsp 내용이 반환되는 것을 보니...) ParserError가 발생한다.... 


datatype : json 인데 url이 없다 보니 / 를 참조하고...... 일반적으로 읽혀지는 index가 읽혀져서 html tag가 반환되니 parsererror unexpected token이 발생했다.


그래서 datatype:local로 변경하고 이벤트 발생시에 datatype:json 으로 재변경하도록 하였다.


변경된 jqgrid 초기 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
jQuery("#grid").jqGrid({
        datatype: "local", 
        //가져온 데이터를 읽을 때 사용
        jsonReader: {
             root: "rows",
             page: "page",
             total: "total",
             records: "records",
             repeatitems: true,
             cell: "cell",
             id: "id"
        },                                                     //json형태로 데이터 받음. 
        height: 550,
        autowidth: true,
        colNames:['예약일시','휴양소명','휴양소id','예약번호','객실명','객실id','지망','사번','성명','연락처','확정'],    //컬럼 구성요소
        colModel:[  
            //각 컬럼에 바인딩될 json 키값
            {name:'stay_start_date',index:'stay_start_date', width:100, align: 'center', sortable:true, formatter:'srcformat' },
            {name:'rnrc_name',index:'rnrc_name', width:100, align: 'center', sortable:true },
            {name:'rnrc_id',index:'rnrc_id', width:100, align: 'center', sortable:true, hidden:true },
            {name:'reserved_id',index:'reserved_id', width:100, align: 'center', sortable:true, hidden:true },
            {name:'room_name',index:'room_name', width:100, align: 'center', sortable:true },
            {name:'room_id',index:'room_id', width:100, align: 'center', sortable:true, hidden:true  },
            {name:'ranking',index:'ranking', width:100, align: 'center', sortable:true },            
            {name:'emp_no',index:'emp_no', width:100, align: 'center', sortable:true },           
            {name:'name',index:'name', width:100, align: 'center', sortable:true },
            {name:'phone_no',index:'phone_no', width:100, align: 'center', sortable:false },
            {name:'fix_flag',index:'fix_flag', width:100, align: 'center', sortable:true, formatter:formatOpt1}
        ],    
        rowNum: 1000,                             //기본 row 수 request 시 rows로 받으면 됨.
        //rowList:[5,10,30],                   //rowNum 수 변경 
        rowTotal: 2000,                  
        rownumbers : true,                      //리스트 순번
        autoencode: true,
        //viewrecords: true,                      //하단 레코드 수 표시 유무
        emptyrecords : '결과가 없습니다.',      //row가 없을 경우 출력 할 text
        multiselect: true,                     //전체선택 체크박스 유무, 테이블에서 row 체크를 멀티로 할 수 있는 옵션.
        gridview: true,
        mtype: "GET", 
        loadtext: "데이타 로딩중..... 잠시 기다려 주십시오.",
        caption: "예약신청자 일람",  
        sortable: true,
        loadonce: false,
        onPaging: function (pgButton) {
            // 페이징 확인용 
            var newUserValue = $('input.ui-pg-input', "#pg_pagerId").val();
            var newValue = 0;
            var currentValue = $("#grid").getGridParam('page');
            if (pgButton.indexOf("next") >= 0)
                newValue = ++currentValue;
            else if (pgButton.indexOf("prev") >= 0)
                newValue = --currentValue;
            else if (pgButton.indexOf("last") >= 0)
                newValue = $("#grid").getGridParam('lastpage');
            else if (pgButton.indexOf("first") >= 0)
                newValue = 1;
            else if (pgButton.indexOf("user") >= 0)
                newValue = newUserValue;
            // 페이징 확인용 끝    
            
            /* 
            * searchBtn 과 페이징 버튼을 구분하기 위해서 
            * 페이징 버튼을 눌렀을 때는 searchBtn이 없는 url을 그리드에 셋팅함.
            **/
            $("#grid").jqGrid('setGridParam', {datatype: "json"url:"/rnrc_a03/rnrcGridInfoList.do?from="+ $('#from').val()
                                                             + "&to="+ $('#to').val() 
                                                             + "&rnrc_id=" + $('#selectPension').val()
                                                             + "&room_id=" + $('#selectRoom').val()
                                                             + "&emp_no=" + $('#selectEmp').val()
                                                             + "&fix_flag=" + $('#fix_flag').val()
                                                             })
            
        },
        loadError: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText); 
            alert('HTTP status code: ' + jqXHR.status + '\n' + 'textStatus: ' + textStatus + '\n' + 'errorThrown: ' + errorThrown);
            console.log('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
            //jQuery("#grid").html("Type: "+ textStatus +"; Response: "+ jqXHR.status + " " + jqXHR.statusText);
            
        },
        
        sortname: 'stay_start_date',
        sortorder: 'asc',
        //toppager: true,                       //상단에 페이저 추가        
        //pagerpos: 'center',                     //페이징 위치
        //pgbuttons: true,                        //페이징 버튼 유무
        //pginput: true,                          //페이징 인풋입력 유무
        pager : '#gridpager',
        //recordtext:"총 {2} 건 중 {0} 건 부터 {1}건 까지의 데이타입니다."
    });


변경된 jqgrid reload.

1
2
3
4
5
6
7
8
$("#grid").jqGrid('setGridParam', {datatype: "json", url:"/rnrc_a03/rnrcGridInfoList.do?from="+ $('#from').val()
                                                             + "&to="+ $('#to').val() 
                                                             + "&rnrc_id=" + $('#selectPension').val()
                                                             + "&room_id=" + $('#selectRoom').val()
                                                             + "&emp_no=" + $('#selectEmp').val()
                                                             + "&fix_flag=" + $('#fix_flag').val()
                                                             + "&searchStatus=" + id                                                             
                                                             }).trigger("reloadGrid");


이리하여 Jqgrid의 parserError는 더 이상 나타나지 않는다. 원하는 형태의 loaderror 옵션도 잘 적용된다.


Jqgrid 는 

"who can answer jqgrid questions better than Oleg"

Oleg가 해답이다.









'javascript&Jquery' 카테고리의 다른 글

jquery cookie  (0) 2011.06.27
2013. 12. 26. 16:03

sysdate라던가,,,, Mysql에서 임의로 만들었던 시퀀스용 함수 netxtval() 등을 변경하는 것 외에

limit를 사용한 쿼리도 수정이 되어야 한다.


Mysql

SELECT USE_DTIME FROM tpo_transreltr WHERE ECASH_ID = #ecash_id# order by use_dtime desc limit 1 


SELECT USE_DTIME FROM tpo_transreltr WHERE ECASH_ID = #ecash_id# order by use_dtime desc limit 1m,10


오라클

SELECT USE_DTIME FROM (SELECT USE_DTIME FROM tpo_transreltr WHERE ECASH_ID = #ecash_id# order by use_dtime desc) WHERE rownum=1;


SELECT USE_DTIME FROM (SELECT USE_DTIME FROM tpo_transreltr WHERE ECASH_ID = #ecash_id# order by use_dtime desc) WHERE rownum between ? and ?


로 변경해 주어야 한다.


참고로...DB 드라이버에 따라 틀린지 정확히 알 수 없으나

TO_CARH(TO_DATE ....) 와 같이 연달아 함수가 호출되는 경우는 'yyyymmdd' 같은 포맷스트링을 각각 지정해 주어야 에러가 없이 수행되었다.

EX)

TO_CAHR(TODATE(sysdate,'yyyymmdd'),'yyyymmdd)

'java' 카테고리의 다른 글

HttpUrlConnection 으로 데이타 넘기기  (8) 2014.05.29