TTP协议的接口测试中,使用到最多的就是GET请求与POST请求,其中POST请求有FORM参数提交请求与RAW请求,下面我将结合HttpClient来实现一下这三种形式:
一.GET请求: GET请求时,参数一般是写在链接上的,代码如下:
1 public void get(String url){ 2 CloseableHttpClient httpClient = null; 3 HttpGet httpGet = null; 4 try { 5 httpClient = HttpClients.createDefault(); 6 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build(); 7 httpGet = new HttpGet(url); 8 httpGet.setConfig(requestConfig); 9 CloseableHttpResponse response = httpClient.execute(httpGet); 10 HttpEntity httpEntity = response.getEntity(); 11 System.out.println(EntityUtils.toString(httpEntity,"utf-8")); 12 } catch (ClientProtocolException e) { 13 e.printStackTrace(); 14 } catch (IOException e) { 15 e.printStackTrace(); 16 }finally{ 17 try { 18 if(httpGet!=null){ 19 httpGet.releaseConnection(); 20 } 21 if(httpClient!=null){ 22 httpClient.close(); 23 } 24 } catch (IOException e) { 25 e.printStackTrace(); 26 } 27 } 28 }
二. POST请求的表单提交方式,代码如下:
1 public void post(String url, Map<String, String> params){ 2 CloseableHttpClient httpClient = null; 3 HttpPost httpPost = null; 4 try { 5 httpClient = HttpClients.createDefault(); 6 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build(); 7 httpPost = new HttpPost(url); 8 httpPost.setConfig(requestConfig); 9 List<NameValuePair> ps = new ArrayList<NameValuePair>(); 10 for (String pKey : params.keySet()) { 11 ps.add(new BasicNameValuePair(pKey, params.get(pKey))); 12 } 13 httpPost.setEntity(new UrlEncodedFormEntity(ps)); 14 CloseableHttpResponse response = httpClient.execute(httpPost); 15 HttpEntity httpEntity = response.getEntity(); 16 System.out.println(EntityUtils.toString(httpEntity,"utf-8")); 17 } catch (ClientProtocolException e) { 18 e.printStackTrace(); 19 } catch (IOException e) { 20 e.printStackTrace(); 21 }finally{ 22 try { 23 if(httpPost!=null){ 24 httpPost.releaseConnection(); 25 } 26 if(httpClient!=null){ 27 httpClient.close(); 28 } 29 } catch (IOException e) { 30 e.printStackTrace(); 31 } 32 } 33 }
三. POST请求的RAW参数传递:
1 public void post(String url, String body){ 2 CloseableHttpClient httpClient = null; 3 HttpPost httpPost = null; 4 try { 5 httpClient = HttpClients.createDefault(); 6 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build(); 7 httpPost = new HttpPost(url); 8 httpPost.setConfig(requestConfig); 9 httpPost.setEntity(new StringEntity(body)); 10 CloseableHttpResponse response = httpClient.execute(httpPost); 11 HttpEntity httpEntity = response.getEntity(); 12 System.out.println(EntityUtils.toString(httpEntity,"utf-8")); 13 } catch (ClientProtocolException e) { 14 e.printStackTrace(); 15 } catch (IOException e) { 16 e.printStackTrace(); 17 }finally{ 18 try { 19 if(httpPost!=null){ 20 httpPost.releaseConnection(); 21 } 22 if(httpClient!=null){ 23 httpClient.close(); 24 } 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 } 29 }