HttpClient在HTTP协议接口测试中的使用

原作者 http://www.cnblogs.com/zhangfei/p/5099036.html

http://www.cnblogs.com/whatlonelytear/articles/4835538.html

 

HTTP协议的接口测试中,使用到最多的就是GET请求与POST请求,其中POST请求有FORM参数提交请求与RAW请求,下面我将结合HttpClient来实现一下这三种形式:

一.GET请求: GET请求时,参数一般是写在链接上的,代码如下:

public void get(String url){
    CloseableHttpClient httpClient = null;
    HttpGet httpGet = null;
    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();     
        httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            if(httpGet!=null){
                httpGet.releaseConnection();
            }
            if(httpClient!=null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


如果想把参数不写在链接上,单独的传进去,则可以这样:

 

 

 

public void get(String url, Map<String, String> params){
    CloseableHttpClient httpClient = null;
    HttpGet httpGet = null;
    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
        String ps = "";
        for (String pKey : params.keySet()) {
            if(!"".equals(ps)){
                ps = ps + "&";
            }
            ps += pKey+"="+params.get(pKey);
        }
        if(!"".equals(ps)){
            url = url + "?" + ps;
        }
        httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            if(httpGet!=null){
                httpGet.releaseConnection();
            }
            if(httpClient!=null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


 二. POST请求的表单提交方式,代码如下:

 

 

 

 

public void post(String url, Map<String, String> params){
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        List<NameValuePair> ps = new ArrayList<NameValuePair>();
        for (String pKey : params.keySet()) {
            ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(ps));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            if(httpPost!=null){
                httpPost.releaseConnection();
            }
            if(httpClient!=null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


三. POST请求的RAW参数传递:

 

 

 

 

public void post(String url, String body){
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setEntity(new StringEntity(body));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            if(httpPost!=null){
                httpPost.releaseConnection();
            }
            if(httpClient!=null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class HttpUtil {
    public static String post_http_request(String url, Map<String, String> params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sb.substring(0, sb.length() - 1);
        }
        System.out.println("send_url:" + url);
        System.out.println("send_data:" + sb.toString());
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
             POST 只能为大写,严格限制,post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值,否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                //buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }
}
 public static String  httpPostForm(String url,List<NameValuePair> nameValuePairList) throws IOException {
        // 创建默认的httpClient实例.
        DefaultHttpClient  client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        System.out.println("-------------url is----------------"+url);

        UrlEncodedFormEntity uefEntity = null;
        try {
            uefEntity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httppost.setEntity(uefEntity);
        // System.out.println("executing request " + httppost.getURI());
        HttpResponse response = null;
        try {
            response = client.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String tmp;
        HttpEntity entity = response.getEntity();
        tmp=EntityUtils.toString(entity, "UTF-8");
        client.getConnectionManager().shutdown();
        return tmp;
    }

 

List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("key","value"));

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值