HTTP POST接口带参数的HttpClient请求方法和调用

接口自动化测试,今天遇到POST接口带参数,参数在url上,发现原来的工具类中没有该方法,重新调试加上。

 doPost方法如下:

    /**
     * 发送POST请求,带请求参数
     * @param url 请求地址
     * @param headers 请求头
     * @param params 请求params
     * @return getHttpClientResult getHttpClientResult方法
     */

    //public static String doPost(String url, JSONObject json,String token) {
    public  HttpClientResult doPost(String url, Map<String, String> headers,Map<String,String> params){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse=null;
        HttpPost httpPost=null;
        HttpClientResult httpClientResult=null;
        //String result="";
        try {
            //1.创建httpClient对象
            //httpClient = HttpClients.createDefault();
            httpClient =createHttpsClient(filePath,passWord);
            // 创建访问的地址
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null) {
                Set<Map.Entry<String, String>> entrySet = params.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue());
                }
            }
            //2.创建httpPost对象
            httpPost = new HttpPost(uriBuilder.build());
            //httpPost = new HttpPost(url);
            //2.1对象设置请求头
            //httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            //httpPost.setHeader("Authorization",token);
            packageHeader(headers, httpPost);
            //2.2封装请求参数
            //packageParam(params, httpPost);

            //2.3对象设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
            httpPost.setConfig(requestConfig);
            //3.使用httpClient发起请求并响应获取response
            /*
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            //4.解析响应,获取数据
            //判断状态码是否是200
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(entity,ENCODING);
                //System.out.println(result);
            }
            //System.out.println(httpResponse.getStatusLine());
            //System.out.println(httpResponse.getStatusLine().getStatusCode());
            //System.out.println(httpResponse.getProtocolVersion());
            //System.out.println(HttpStatus.SC_OK);
            */
            httpClientResult=getHttpClientResult(httpResponse,httpClient,httpPost);
        }
        catch (Exception e){
            log.error(e.toString());
        }
        finally {
            //5.释放资源
            release(httpResponse, httpClient);

        }
        return httpClientResult;
    }

调用:

        String appId="123456789";
        Map<String, String> headers=new HashMap<>();
        headers.put("Content-Type","application/json;charset=UTF-8");
        headers.put("Authorization","Bearer "+token);

    @Test
    public void c06_pluginDeployment() {
        for (ApiDataBean data : listExcel) {
            if (data.getApiName().trim().equals("pluginDeployment")) {
                HttpsClientUtils httpUtils = new HttpsClientUtils();
                String host=BaseRequest.getHost();//这里例如:https://IP
                String reqUrl = host + data.getUrl();   //https://IP+接口url
                System.out.println(reqUrl);
                HttpClientResult httpResult= null;
                try {
                    Map<String, String> params=new HashMap<>();
                    params.put("appId",appId);
                    System.out.println(appId);
                    httpResult = httpUtils.doPost(reqUrl, headers,params);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error(String.valueOf(e));
                }

                String resultContent = httpResult.getContent();
                //int code = JsonPath.read(resultContent, "$.code");
                log.info(resultContent);
            }
        }
    }

参考:

[Java 接口自动化框架]httpclient4.5.3(CloseableHttpClient) https的工具类HttpsClientUtils

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Java提供的HttpURLConnection或者Apache HttpClient库来实现POST请求提交JSON参数。 使用HttpURLConnection实现POST请求提交JSON参数的示例代码如下: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; public class HttpPostJson { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String json = "{\"username\":\"test\",\"password\":\"123456\"}"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 添加请求头 con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); // POST请求 con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(json.getBytes("UTF-8")); os.flush(); os.close(); // 获取返回结果 int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印返回结果 System.out.println(response.toString()); } } ``` 使用Apache HttpClient库实现POST请求提交JSON参数的示例代码如下: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.HttpResponse; import java.io.BufferedReader; import java.io.InputStreamReader; public class HttpPostJson { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String json = "{\"username\":\"test\",\"password\":\"123456\"}"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url); // 设置请求头 request.setHeader("Content-Type", "application/json"); // 设置请求参数 StringEntity params = new StringEntity(json); request.setEntity(params); // POST请求 HttpResponse response = httpClient.execute(request); // 获取返回结果 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } // 打印返回结果 System.out.println(result.toString()); } } ``` 以上示例代码仅供参考,实际使用时需要根据自己的需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宁宁可可

您的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值