设为首页 加入收藏

TOP

使用HttpClient调用接口(二)
2017-10-10 21:06:10 】 浏览:4355
Tags:使用 HttpClient 调用 接口
p;   }


    /**
    * 不带参数的get请求
    *
    * @param url
    * @return
    * @throws Exception
    */
    public HttpResult doGet(String url) throws Exception {
        HttpResult httpResult = this.doGet(url, null);
        return httpResult;
    }


    /**
    * 带参数的post请求
    *
    * @param url
    * @param map
    * @return
    * @throws Exception
    */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);


        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<Nameva luePair> params = new ArrayList<Nameva luePair>();


            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameva luePair(entry.getKey(), entry.getValue().toString()));
            }


            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");


            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }


        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPost);


        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }


        // 返回结果
        return httpResult;
    }


    /**
    * 不带参数的post请求
    *
    * @param url
    * @return
    * @throws Exception
    */
    public HttpResult doPost(String url) throws Exception {
        HttpResult httpResult = this.doPost(url, null);
        return httpResult;
    }


    /**
    * 带参数的Put请求
    *
    * @param url
    * @param map
    * @return
    * @throws Exception
    */
    public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPut httpPut = new HttpPut(url);


        // 判断map不为空
    &nbs

首页 上一页 1 2 3 4 5 下一页 尾页 2/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇二叉树的代码实现 下一篇UNIX环境高级编程 心得笔记

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目