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");
  • 相关阅读:
    词法分析程序
    0909关于编译原理
    深度学习中图像检测的评价标准
    【 记忆网络 1 】 Memory Network
    ssm又乱码
    百度地图标注没了
    Fragment与Activity交互(使用Handler)
    在android里用ExpandableListView实现二层和三层列表
    java中outer的使用
    android中使用Http下载文件并保存到本地SD卡
  • 原文地址:https://www.cnblogs.com/lixianshengfitting/p/13851339.html
Copyright © 2011-2022 走看看