zoukankan      html  css  js  c++  java
  • httpclient学习(环境搭建,发送get,post请求)

    httpclient是一个客户端接口调用框架,实现了http协议的客户端接口调用技术,可以通过模拟测试工具发起接口请求,完成接口调用。

    环境搭建:在pom.xml文件里面添加以下标签

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

     理解什么是接口:

    接口的本质:

    接口测试流程:

    httpclient发送get请求:

    代码实现:

    package com.mg.api.auto;
    
    import java.io.IOException;
    
    import org.apache.http.Header;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    /**
     * httpclient发送get请求
     * 
     * @author admin
     *
     */
    public class GetDemo {
        public static void main(String[] args) throws ClientProtocolException, IOException {
            // 准备url
            String url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
    
            // 准备测试数据
            String tel = "18581232148";
            url += ("?tel=" + tel); // 拼接url
            System.out.println(url);
    
            // 请求方式:get
            HttpGet get = new HttpGet(url);
    
            // 发送请求,获取响应
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse response = httpClient.execute(get);
    
            // 获取响应状态码
            int code = response.getStatusLine().getStatusCode();
            System.out.println(code);
    
            // 获取响应内容
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
    
            // 获取响应头信息
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                System.out.println(header);
            }
        }
    }

    get请求运行结果:

    httpclient发送post请求:

    代码实现:

    package com.mg.api.auto;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.http.Header;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    /**
     * httpclient发送post请求
     * 
     * @author admin
     *
     */
    public class PostDemo {
        public static void main(String[] args) throws ClientProtocolException, IOException {
            // 接口地址
            String loginUrl = "http://49.235.92.12:9000/api/v1/login";
    
            // 接口请求方式:post
            HttpPost post = new HttpPost(loginUrl);
    
            // 接口测试数据
            String username = "test";
            String password = "123456";
            List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
            parameters.add(new BasicNameValuePair("username", username));
            parameters.add(new BasicNameValuePair("password", password));
            post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
    
            // 发送请求,获取响应
            HttpClient client = HttpClients.createDefault(); // 创建默认客户端,相当于按钮
            HttpResponse response = client.execute(post);
    
            // 状态码
            int code = response.getStatusLine().getStatusCode();
            System.out.println("状态码:" + code);
    
            // 响应报文
            String result = EntityUtils.toString(response.getEntity()); // json转为string
            System.out.println("响应报文:" + result);
    
            // 获取响应头信息
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                System.out.println("响应头信息:" + header);
            }
        }
    
    }

    post请求运行结果:

    常用HttpResponse响应方法:

    封装后的post和get请求:

    post请求:

    package com.mg.tools;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    /**
     * 接口调用post工具
     * 
     * @author admin
     *
     */
    public class SendPost {
        public static void main(String[] args) {
            // 接口地址
            String url = "http://49.235.92.12:9000/api/v1/login";
            // 测试数据
            String username = "test";
            String password = "123456";
            Map<String, String> params = new HashMap<String, String>();
            // 将数据添加到map里面
            params.put("username", username);
            params.put("password", password);
            // 传入参数,调用方法发送请求
            System.out.println(sendPost(url, params));
        }
    
        /**
         * post请求处理接口
         * 
         * @param url:请求url地址
         * @param params:请求参数map形式添加
         * @return
         */
        public static String sendPost(String url, Map<String, String> params) {
    
            // 接口请求方式:post
            HttpPost post = new HttpPost(url);
            List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    
            // 取出map中所有的参数名
            Set<String> keys = params.keySet();
    
            // 通过循环将参数保存到list集合里面
            for (String key : keys) {
                String value = params.get(key);
                parameters.add(new BasicNameValuePair(key, value));
            }
            // 定义全局变量,便于返回结果
            String result = "";
    
            try {
                post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
                // 发送请求,获取响应
                HttpClient client = HttpClients.createDefault(); // 创建默认客户端,相当于按钮
                HttpResponse response = client.execute(post);
    
                // 状态码
                int code = response.getStatusLine().getStatusCode();
                System.out.println("状态码:" + code);
    
                // 响应报文
                result = EntityUtils.toString(response.getEntity());
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return "响应报文:" + result;
        }
    
    }

    get请求:

    package com.mg.tools;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    /**
     * 接口调用get工具
     * 
     * @author admin
     *
     */
    public class SendGet {
        public static void main(String[] args) {
            // 准备url
            String url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
            // 准备测试数据
            String tel = "18581232148";
            Map<String, String> params = new HashMap<String, String>();
            params.put("tel", tel);
            System.out.println(sendGet(url, params));
        }
    
        /**
         * @param url:请求url地址
         * @param params:请求参数map形式添加
         * @return
         */
        public static String sendGet(String url, Map<String, String> params) {
    
            Set<String> keys = params.keySet();
            // 标识位
            int mark = 1;
            for (String key : keys) {
                if (mark == 1) {
                    url += ("?" + key + "=" + params.get(key));
                } else {
                    url += ("&" + key + "=" + params.get(key));
                }
                mark++;
            }
            System.out.println("url=" + url);
    
            // 请求方式:get
            HttpGet get = new HttpGet(url);
    
            // 发送请求,获取响应
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse response;
    
            String result = "";
    
            try {
                response = httpClient.execute(get);
                // 获取响应状态码
                int code = response.getStatusLine().getStatusCode();
                System.out.println("响应状态码:" + code);
    
                // 获取响应内容
                result = EntityUtils.toString(response.getEntity());
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return "响应报文:" + result;
        }
    }

    HttpUtil工具类:

    package com.mg.api.auto_v1;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    /**
     * 接口调用工具类,post和get
     * 
     * @author admin
     *
     */
    public class HttpUtil {
        /**
         * post请求处理接口
         * 
         * @param url:请求url地址
         * @param params:请求参数map形式添加
         * @return
         */
        public static String sendPost(String url, Map<String, String> params) {
    
            // 接口请求方式:post
            HttpPost post = new HttpPost(url);
            List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    
            // 取出map中所有的参数名
            Set<String> keys = params.keySet();
    
            // 通过循环将参数保存到list集合里面
            for (String key : keys) {
                String value = params.get(key);
                parameters.add(new BasicNameValuePair(key, value));
            }
            // 定义全局变量,便于返回结果
            String result = "";
    
            try {
                post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
                // 发送请求,获取响应
                HttpClient client = HttpClients.createDefault(); // 创建默认客户端,相当于按钮
                HttpResponse response = client.execute(post);
    
                // 状态码
                int code = response.getStatusLine().getStatusCode();
                System.out.println("状态码:" + code);
    
                // 响应报文
                result = EntityUtils.toString(response.getEntity());
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return "响应报文:" + result;
        }
    
        /**
         * get请求处理接口
         * 
         * @param url
         * @param params
         * @return
         */
        public static String sendGet(String url, Map<String, String> params) {
            Set<String> keys = params.keySet();
            // 标识位
            int mark = 1;
            for (String key : keys) {
                if (mark == 1) {
                    url += ("?" + key + "=" + params.get(key));
                } else {
                    url += ("&" + key + "=" + params.get(key));
                }
                mark++;
            }
            System.out.println("url=" + url);
    
            // 请求方式:get
            HttpGet get = new HttpGet(url);
    
            // 发送请求,获取响应
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse response;
    
            String result = "";
    
            try {
                response = httpClient.execute(get);
                // 获取响应状态码
                int code = response.getStatusLine().getStatusCode();
                System.out.println("响应状态码:" + code);
    
                // 获取响应内容
                result = EntityUtils.toString(response.getEntity());
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return "响应报文:" + result;
        }
    }
  • 相关阅读:
    [C++再学习系列] 深入new/delete:Operator new的全局重载
    [C++再学习系列] 函数模板和类模板
    [C++再学习系列] 模板函数的自定义点
    [C++再学习系列] STL容器删除操作总结
    How to create a sizelimited filesystem
    CodeSmith 破解和注册
    LINQ to SQL学习的几个问题
    SQLSERVER2005 分区表
    google工具栏和搜狗拼音叠加问题
    C#中构成函数重载有哪些条件和特征?
  • 原文地址:https://www.cnblogs.com/xiamaojjie/p/12258902.html
Copyright © 2011-2022 走看看