HttpClient의 간단한 입문 실례, get 및post 요청 보내기

2167 단어

1 get 요청 보내기

    /**
     * HttpClient get 
     * @param url  
     * @return
     * @throws IOException
     */
    public static String httpGet(String url) throws IOException {
        String result = "";

        // HttpClient 
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        // get 
        HttpResponse response = httpClient.execute(httpGet);

        /** , **/
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            /** json **/
            result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            return result;
        }
        return result;
    }

 

2 post 요청 보내기 (파라미터 포함)

    /**
     * HttpClient post 
     * @param url  
     * @param jsonParam  (json xml )
     * @param type  
     * @return
     * @throws IOException
     */
    public static String httpPost(String url, String jsonParam, String type) throws IOException {
        String result = "";

        // HttpClient 
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        if (jsonParam != null) {
            // 
            StringEntity entity = new StringEntity(jsonParam, "utf-8");
            entity.setContentEncoding("UTF-8");
            if (type.equals("json")) {
                entity.setContentType("application/json");
            }
            if (type.equals("xml")) {
                entity.setContentType("application/xml");
            }

            httpPost.setEntity(entity);
        }
        // post 
        HttpResponse response = httpClient.execute(httpPost);
        /** , **/
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            /** json **/
            result = EntityUtils.toString(response.getEntity());
            System.out.print(result);
            return new String(result.getBytes("ISO-8859-1"), "UTF-8");
        }
        return result;
    }

좋은 웹페이지 즐겨찾기