sitelink1  
sitelink2  
sitelink3  
extra_vars4  
extra_vars5  
extra_vars6  

jQuery에서 JSON 데이터로 http request 를 요청하는데

생각해보니 HttpServlet 클래스에서 JSON을 위해 특별히 지원해주는 API는 없었다

그동안 습관적으로 jQuery로 JSON데이터를 보내면 서버에서 HttpServletRequest.getParameter() 로 데이터를 꺼냈었는데

결국 HttpServlet 는 Get과 Post 방식의 파라미터 값만 주고 받을뿐이다

 

이제서야 우연히 발견하였는데

jQuery에서 열심히 JSON데이터를 만들어서 보내면

jQuery가 서버에는 POST데이터로 변환한 형태로 보낸 것 같다 (jQuery레퍼런스를 보면 되겠지만 귀찮음...)

생각해보니 JSON데이터나 POST데이터나 데이터 특성이 유사해보인다

그래서 jQuery에서 포맷 변환을 하는 것 같다 (정말로 그런지는 잘 모름)

 

 

jQuery 샘플코드

var postData = {

    CMD : "GET_KB_PROJECTLIST"

};

        

$.ajax({

    type : "post",

    url : serviceURL,

    data : postData,

    contentType: "application/x-www-form-urlencoded; charset=UTF-8",

    dataType : "json",

    success : function(resJo) {

        if (resJo.RTN_CODE == -1) {

            thisP.alert(resJo.RTN_MSG);

        } else {

            var nRow = -1;

            for (var i=0;i<resJo.result.length;i++) {

                if (resJo.result[i].owner_id == "7") {

                    nRow = thisP.Dataset00.addRow();

                    thisP.Dataset00.setColumn(nRow, "CODE", resJo.result[i].id)

                    thisP.Dataset00.setColumn(nRow, "DATA", resJo.result[i].name)

                }

            }

        }

    },

    complete : function(data) {

        ;

    },

    error : function(xhr, status, error) {

        trace("xhr="+xhr);

        trace("status="+status);

        trace("error"+error);

    }

});

 

Servlet 샘플코드

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

    String cmd = req.getParameter("CMD");

 

    ... ... ...

}

 

 

 

근데 PHP어플리케이션(예> Kanboard) 에서 Rest API를 제공하는데 PHP어플리케이션 서버로 Request 요청시 JSON데이터 문자열을 직접 전달 가능하다

데이터 자체가 name, value 형태가 아닌 JSON String으로 전달되어도 PHP어플리케이션이 JSON데이터를 문제없이 Parsing하는 것 같다

반대로 POST데이터는 인식을 안할듯... 확인해보면 알겠지만 귀찮음

 

Servlet 샘플코드

URL url = new URL(urlStr != null ? urlStr : this.URL);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setDoInput(true);

    

byte[] xApiAuthTokenBytes = String.join(":", userStr != null ? userStr : this.USER, apitokenStr != null ? apitokenStr : this.APITOKEN).getBytes("utf-8");

String xApiAuthToken = Base64.getEncoder().encodeToString(xApiAuthTokenBytes);

connection.setRequestProperty("X-API-Auth", xApiAuthToken);

connection.setRequestProperty("Authorization", "Basic " + xApiAuthToken); //인증오류로 인해 추가함

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

    

connection.setRequestMethod("POST");

connection.setDoOutput(true);

    

OutputStream out_stream = null;

BufferedReader brin = null;

String resStr = null;

StringBuffer resStrBuff = new StringBuffer();

    

try {

    out_stream = connection.getOutputStream();

    out_stream.write(jsonStr.getBytes("UTF-8")); //JSON데이터를 문자열로 추출한 데이터를 그대로 보낸다

    out_stream.flush();

    out_stream.close();

 

    brin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

    while ((resStr = brin.readLine()) != null) {

        resStrBuff.append(resStr);

    }

} catch (IOException ioe) {

    System.out.println("<RDEnv> Kanboard 접속이 불가합니다 - "+ioe);

} finally {

    if (brin != null) {

        brin.close();

        brin = null;

    }

    out_stream = null;

    connection = null;

    url = null;

    resStr = null;

}

if (resStrBuff.length() > 0) {

    JSONParser parser = new JSONParser();

    Object obj = parser.parse(resStrBuff.toString());

    JSONObject jsonObject = (JSONObject) obj;

    return jsonObject;

}

 

번호 제목 글쓴이 날짜 조회 수
21 com.fasterxml.jackson 을 이용한 json data 작성 예제 황제낙엽 2025.10.17 2
20 [ChatGPT] JsonNode 객체에서 asText()와 toString() 의 차이점 황제낙엽 2025.06.30 4
19 [Gemini, Jackson] JsonNode의 asText(), textValue(), toString() 함수들과 ObjectMapper.writeValueAsString() 함수 황제낙엽 2025.02.06 212
18 [ChatGPT] json data 의 정렬 (jackson, json simple, gson) 황제낙엽 2024.07.23 400
17 [Gemini] HttpURLConnection 클래스를 이용한 데이터 전송 방식 비교 황제낙엽 2024.03.14 1069
16 [JsonNode] depth 가 여러 단계인 json data 내부를 조회하는 java code 예제 (from Bard) file 황제낙엽 2023.08.09 1038
15 HttpServletRequest, HttpServletResponse, JSONObject, POST 황제낙엽 2022.01.12 722
» jQuery JSON 데이터 통신의 특성 (HttpServletRequest) 황제낙엽 2019.06.23 740
13 JSON과 GSON 황제낙엽 2019.03.24 749
12 [HttpURLConnection, HttpsURLConnection] 코드참조용 샘플프로젝트 secret 황제낙엽 2019.01.18 0
11 json-rpc 에서 한글 문제 황제낙엽 2018.08.08 741
10 Calendar, Date, Format, java.time 패키지 황제낙엽 2017.10.31 756
9 JSON Util (JSON 을 다루기 위해 직접 작성한 유틸 클래스) file 황제낙엽 2017.07.10 990
8 JSON 라이브러리(API) 종류 황제낙엽 2017.01.18 910
7 [JSON기초04] 자바 JSON 데이터에서 KEY 값 알아오기 (TIP) 황제낙엽 2017.01.18 7580
6 [JSON기초03] 자바 JSON Google Simple JSON을 이용한 간단한 JSON DATA 파싱 황제낙엽 2017.01.18 1137
5 [JSON기초02] 자바 JSON Google Simple JSON을 이용한 간단한 JSON DATA 생성 황제낙엽 2017.01.18 663
4 [JSON기초01] JSON이란? XML이란? JSON 개념, XML 개념 설명 황제낙엽 2017.01.18 872
3 JSON-lib Java Library file 황제낙엽 2013.04.09 630
2 servlet 에서의 json 한글처리 황제낙엽 2013.04.23 2201