JAVA+Maven+TestNG+Jenkins 인터페이스 자동화 프레임워크 구축 (3)HttpClient 기반 http 요청 봉인

6107 단어
     

package utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
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.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    private static CloseableHttpClient client;
    private static RequestConfig config;

    //   
    static {
        config = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(20000).build();
        client = HttpClients.custom().build();
    }

    public static String doGet(String url, Map param, final Map header){
        if (url.isEmpty()){
            return null;
        }
        try{
            //  url
            if (param.size() > 0){
                List pairs = new ArrayList();
                for (Map.Entry entry: param.entrySet()){
                    String value = entry.getValue();
                    if (!value.isEmpty()){
                        pairs.add(new BasicNameValuePair(entry.getKey(),value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs),"UTF-8");
            }

            HttpGet httpGet = new HttpGet(url);

            //     
            if (header.size() > 0){
                header.forEach((key,value) -> httpGet.setHeader(key,value));
            }
            CloseableHttpResponse response = client.execute(httpGet);

            //        
            int code = response.getStatusLine().getStatusCode();
            if (code != 200 ){
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + code);
            }

            //      
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }

            //    ,    
            EntityUtils.consume(entity);
            response.close();
            return result;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    public static String doPostByJson(String url, String json, final Map header){
        if (url.isEmpty()){
            return null;
        }
        try{

            //     
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(json, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            //     
            if (header.size() > 0){
                header.forEach((key,value) -> httpPost.setHeader(key,value));
            }

            CloseableHttpResponse response = client.execute(httpPost);

            //        
            int code = response.getStatusLine().getStatusCode();
            if (code != 200 ){
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + code);
            }

            //      
            HttpEntity responseEntity = response.getEntity();
            String result = null;
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity, "UTF-8");
            }
            EntityUtils.consume(responseEntity);

            //    ,    
            response.close();
            return result;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String doPostByFORM(String url, Map form, final Map header){
        if (url.isEmpty()) {
            return null;
        }

        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("content-Type", "application/x-www-form-urlencoded");

            if (header.size() > 0) {
                header.forEach((key,value) -> httpPost.setHeader(key,value));
            }
            //form  
            if (form.size() > 0) {
                ArrayList list = new ArrayList<>();
                form.forEach((key, value) -> list.add(new BasicNameValuePair(String.valueOf(key), String.valueOf(value))));
                httpPost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
            }

            response = client.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }

            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return null;
    }
    
}

좋은 웹페이지 즐겨찾기