본문 바로가기
Java

[Java] POST 데이터 전송(application/x-www-form-urlencoded) 구현

by jn4624 2022. 4. 26.
반응형

1. application/json과 application/x-www-form-urlencoded

application/json은 {key: value}의 형태로 전송되지만 application/x-www-form-urlencoded는 key=value&key=value의 형태로 전달된다.

즉 application/x-www-form-urlencoded는 보내는 데이터를 URL인코딩 이라고 부르는 방식으로 인코딩 후에 웹서버로 보내는 방식을 의미한다.

 

public JSONObject httpPost(String url, HashMap<String, Object> param) {
    JSONObject jsonObj = null;

    try {

        // TLS/SSL 통신 무시
        TrustManager[] trustAllcerts = new TrustManager[] {
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { }
                }
        };

        // SSL INIT
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllcerts, new SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
            public boolean verify(String string, SSLSession ssls){
                return true;
            }
        });

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

            for( String key : param.keySet() ) {
                map.add(key, (String) param.get(key));
            }

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(map, headers);

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

            JSONParser jsonParser = new JSONParser();
            String getBody = responseEntity.getBody();
            jsonObj = (JSONObject) jsonParser.parse(getBody);
        } catch(Exception e) {
            e.printStackTrace();
            jsonObj = null;
        }
    } catch(Exception e) {
        e.printStackTrace();
    }

    return jsonObj;
}

 

 

🙏 참조 ::

반응형