zoukankan      html  css  js  c++  java
  • java httpclient接口自动化

    环境准备:

    idea 在pom文件中引入依赖包

            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>4.4.4</version>
            </dependency>

    先初始化一些参数和实例

    String url;  //请求地址
    CloseableHttpClient httpClient; //用来发送http请求的HttpClient实例
    CloseableHttpResponse httpResponse; //用来接受响应信息的实例
    String responseBody; //存储响应主体

    创建get请求:

    //创建一个httpClient的实例  
    httpClient = HttpClients.createDefault();  
    //创建一个httpGet请求实例
    HttpGet httpGet = new HttpGet(url);  
    //使用httpClient实例发送刚创建的get请求,并用httpResponse将反馈接收
    httpResponse = httpClient.execute(httpGet);
    //处理响应
    HttpEntity entity = httpResponse.getEntity();
    responseBody = EntityUtils.toString(entity,"tuf-8");

    创建post请求:

    //创建一个httpClient的实例  
    httpClient = HttpClients.createDefault();  
    //创建一个httpGet请求实例
    HttpPost httpPost = new HttpPost(url);  
    //添加参数params
    Map<String, String> params = new HashMap<String, String>();
            params.put("username","ceshi1");
            params.put("password","123456");
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            post.setEntity(new UrlEncodedFormEntity(formParams, "utf-8"));
    //使用httpClient实例发送刚创建的get请求,并用httpResponse将反馈接收
    httpResponse = httpClient.execute(httpPost);
    //处理响应
    HttpEntity entity = httpResponse.getEntity();
    responseBody = EntityUtils.toString(entity,"utf-8");
  • 相关阅读:
    【C/C++】qsort函数的使用方法和细节
    MOOC C++笔记(五):继承
    MOOC 数据库系统笔记(二):数据库系统的基本结构及其演变发展
    PTA A1015
    MOOC 数据库系统笔记(一):初步认识数据库系统
    PTA A1014
    MOOC C++笔记(四):运算符重载
    PTA A1013
    PTA A1011&A1012
    1.1.22 同样的文档,行数不一样
  • 原文地址:https://www.cnblogs.com/lixianshengfitting/p/13851339.html
Copyright © 2011-2022 走看看