시행착오/[java]

[java] HTTP request POST 보내는 법 - 예시 코드 / (추가) 한글깨짐 현상 해결

bled 2021. 4. 8. 09:22
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpClientExample {

    // one instance, reuse
    private final CloseableHttpClient httpClient = HttpClients.createDefault();

    public static void main(String[] args) throws Exception {

        HttpClientExample obj = new HttpClientExample();

        try {            
            System.out.println("Send Http POST request");
            obj.sendPost();
        } finally {
            obj.close();
        }
    }

    private void close() throws IOException {
        httpClient.close();
    }

    private void sendPost() throws Exception {

        HttpPost post = new HttpPost("https://httpbin.org/post");
        // add request headers 헤더 추가
        post.addHeader("key", "65435213245");

        // add request parameter, form parameters 파라미터 추가
        List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("username", "abc"));
        urlParameters.add(new BasicNameValuePair("password", "123"));
        urlParameters.add(new BasicNameValuePair("custom", "secret"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(post)) {

            System.out.println(EntityUtils.toString(response.getEntity()));
        }

    }

}

 

    <!-- pom.xml -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.10</version>
    </dependency>

mkyong.com/java/how-to-send-http-request-getpost-in-java/

 

How to send HTTP request GET/POST in Java - Mkyong.com

- How to send HTTP request GET/POST in Java

mkyong.com

(추가) 한글 깨짐 현상 발생

post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");  

추가해도 해결되지 않음

post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); 

"UTF-8" 을 넣으니 해결됨

참고)

helloworld92.tistory.com/3