HttpClient的日常使用

一、代码案例


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @author rick
 * @create 2022/2/22 15:53
 */
@Slf4j
public class HttpClientUtils {

    private static String cookiee;

    public static String setCookie(Cookie cookie) {
        cookiee = null;
        return cookiee = cookie.getValue();
    }

    public static String getCookie() {
        return cookiee;
    }

    public static String doGet(String url) {
        // 输入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        // 创建httpClient实例
        HttpClient httpClient = new HttpClient();
        // 设置http连接主机服务超时时间:15000毫秒
        // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建一个Get方法实例对象
        GetMethod getMethod = new GetMethod(url);
        // 设置get请求超时为60000毫秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
        try {
            // 执行Get方法
            int statusCode = httpClient.executeMethod(getMethod);
            // 判断返回码
            if (statusCode != HttpStatus.SC_OK) {
                // 如果状态码返回的不是ok,说明失败了,打印错误信息
                System.err.println("Method faild: " + getMethod.getStatusLine());
            } else {
                // 通过getMethod实例,获取远程的一个输入流
                is = getMethod.getResponseBodyAsStream();
                // 包装输入流
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                // 读取封装的输入流
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp).append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 释放连接
            getMethod.releaseConnection();
        }
        return result;
    }


    public static String doGetFile(String url, OutputStream outputStream) {
        // 输入流
        InputStream imageStream = null;
        BufferedReader br = null;
        String result = null;
        // 创建httpClient实例
        HttpClient httpClient = new HttpClient();
        // 设置http连接主机服务超时时间:15000毫秒
        // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建一个Get方法实例对象
        GetMethod getMethod = new GetMethod(url);
        // 设置get请求超时为60000毫秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
        try {
            // 执行Get方法
            int statusCode = httpClient.executeMethod(getMethod);
            // 判断返回码
            if (statusCode != HttpStatus.SC_OK) {
                // 如果状态码返回的不是ok,说明失败了,打印错误信息
                System.err.println("Method faild: " + getMethod.getStatusLine());
            } else {
                // 通过getMethod实例,获取远程的一个输入流
                imageStream = getMethod.getResponseBodyAsStream();
                // 输出图片内容
                byte[] b = new byte[1024];
                int len;
                while ((len = imageStream.read(b, 0, 1024)) != -1) {
                    outputStream.write(b, 0, len);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != imageStream) {
                try {
                    imageStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 释放连接
            getMethod.releaseConnection();
        }
        return result;
    }


    public static String doPost(String url, Map<String, Object> paramMap) {
        HttpClientUtils.cookiee = null;

        // 获取输入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // 设置httpClient连接主机服务器超时时间:15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建post请求方法实例对象
        PostMethod postMethod = new PostMethod(url);
        // 设置post请求超时时间
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        NameValuePair[] nvp = null;
        // 判断参数map集合paramMap是否为空
        if (null != paramMap && paramMap.size() > 0) {// 不为空
            // 创建键值参数对象数组,大小为参数的个数
            nvp = new NameValuePair[paramMap.size()];
            // 循环遍历参数集合map
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            // 获取迭代器
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();
            int index = 0;
            while (iterator.hasNext()) {
                Entry<String, Object> mapEntry = iterator.next();
                // 从mapEntry中获取key和value创建键值对象存放到数组中
                try {
                    nvp[index] = new NameValuePair(mapEntry.getKey(),
                            new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                index++;
            }
        }
        // 判断nvp数组是否为空
        if (null != nvp && nvp.length > 0) {
            // 将参数存放到requestBody对象中
            postMethod.setRequestBody(nvp);
        }
        // 执行POST方法
        try {
            int statusCode = httpClient.executeMethod(postMethod);
            // 判断是否成功
            if (statusCode != HttpStatus.SC_OK) {
                log.error("獲取 cookie 失败 !!Method faild: " + postMethod.getStatusLine());
            }

            // 判断是否成功
            if (statusCode == HttpStatus.SC_OK) {
                Cookie[] cookies = httpClient.getState().getCookies();
                setCookie(cookies[0]);
            }

            // 获取远程返回的数据
            is = postMethod.getResponseBodyAsStream();
            // 封装输入流
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp).append("\r\n");
            }

            result = sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 释放连接
            postMethod.releaseConnection();
        }
        return result;
    }

    /**
     *  针对对方为 @RequestBody 的这种rest风格的时候,我们才用这个JSON方式去请求。 案例:
     *
     * @param url
     * @param paramMap
     * @return
     */

    public static String doPostJson(String url, Map<String, Object> paramMap)  {

        // 获取输入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // 设置httpClient连接主机服务器超时时间:15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建post请求方法实例对象
        PostMethod postMethod = new PostMethod(url);
        // 设置post请求超时时间
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        NameValuePair[] nvp = null;
        // 判断参数map集合paramMap是否为空
        if (null != paramMap && paramMap.size() > 0) {// 不为空
            // 创建键值参数对象数组,大小为参数的个数
            nvp = new NameValuePair[paramMap.size()];
            // 循环遍历参数集合map
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            // 获取迭代器
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();
            int index = 0;
            while (iterator.hasNext()) {
                Entry<String, Object> mapEntry = iterator.next();
                // 从mapEntry中获取key和value创建键值对象存放到数组中
                try {
                    nvp[index] = new NameValuePair(mapEntry.getKey(),
                            new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                index++;
            }
        }
        // 执行POST方法
        try {
            // 判断nvp数组是否为空
            if (null != nvp && nvp.length > 0) {
                // 将参数存放到requestBody对象中
                postMethod.setRequestBody(nvp);
                postMethod.addRequestHeader("Accept", "application/json");
                postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8;");
                postMethod.setRequestEntity(new StringRequestEntity(nvp[0].getValue(), "application/json", "UTF-8"));
            }

            int statusCode = httpClient.executeMethod(postMethod);
            // 判断是否成功
            if (statusCode != HttpStatus.SC_OK) {
                log.error("獲取 cookie 失败 !!Method faild: " + postMethod.getStatusLine());
            }

            // 获取远程返回的数据
            is = postMethod.getResponseBodyAsStream();
            // 封装输入流
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp).append("\r\n");
            }

            result = sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 释放连接
            postMethod.releaseConnection();
        }
        return result;
    }
}

二、案例讲解:

1、doPostJson方法 与@RequestBody请求体

比如我这里需要发起请求:

    /**
     * 审批-完成该节点任务
     * @return
     */
    @RequestMapping(value = "/completeTask/{taskId}", method = RequestMethod.POST)
    public void getMsg(@PathVariable("taskId") String taskId, @RequestBody(required = false) Map<String, Object> variables) throws IOException {
        //http://localhost:9001 可以作为配置项,后期换域名端口生产等都可以直接替换
        String url = "http://localhost:9001/task/manage/completeTask/" + taskId;
        variables.put("userName","admin");
        // {"deptleaderapprove":"true","hr":"admin","comment":""}

        Map<String,Object> hashMap = new HashMap<>(1);
        hashMap.put("variables",JSON.toJSONString(variables));
        HttpClientUtils.doPostJson(url, hashMap);

    }

// 第二种 就是增加入参@RequestBody String userName:

    /**
     * 审批-完成该节点任务
     * @return
     */
    @RequestMapping(value = "/completeTask/{taskId}", method = RequestMethod.POST)
    public void getMsg(@PathVariable("taskId") String taskId, @RequestBody(required = false) Map<String, Object> variables) throws IOException {
        //http://localhost:9001 可以作为配置项,后期换域名端口生产等都可以直接替换
        String url = "http://localhost:9001/task/manage/oaCompleteTask/" + taskId;
//        variables.put("userName","admin");
        // {"deptleaderapprove":"true","hr":"admin","comment":""}

        Map<String,Object> hashMap = new HashMap<>(1);
        hashMap.put("variables",JSON.toJSONString(variables));
        // 主要是增加这里********************
        hashMap.put("userName","admin");
        HttpClientUtils.doPostJson(url, hashMap);

    }


对应服务方:

    @ApiOperation("办理一个用户任务")
    @RequestMapping(value = "/completeTask/{taskId}", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult completeTask(@PathVariable("taskId") String taskId, @RequestBody(required = false) Map<String, Object> variables) {
        SysUser user = getSysUser();
        String username = user.getLoginName();
        return success();
    }


// 第二种增加了入参: @RequestBody String userName

    @ApiOperation("OA办理一个用户任务")
    @RequestMapping(value = "/oaCompleteTask/{taskId}", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult oaCompleteTask(@PathVariable("taskId") String taskId, @RequestBody String userName, @RequestBody(required = false) Map<String, Object> variables) {

        taskService.setAssignee(taskId, userName);
        return null;

2、普通post请求非JSON格式,采用表单格式提交

请求方

        //入参 获取其他服务的我的待办
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("pageSize", 10);
        paramMap.put("pageNum", 1);
        paramMap.put("userName", "admin");
        String url = "http://localhost:9001/task/manage/mylistByUser";

        String s = HttpClientUtils.doPost(url, paramMap);

服务方:

    /**
     * 查询我的待办任务列表
     */
    @ApiOperation("查询我的待办任务列表")
    @PostMapping("/mylistByUser")
    @ResponseBody
    // ynkj 待办
    public TableDataInfo mylistByUser(TaskInfo param) {
  
        return rspData;
    }

3、GET请求

请求方

    /**
     * 查询审批流的 文件
     * @return
     */
    @RequestMapping(value = "/traceProcess/{processInstanceId}", method = RequestMethod.GET)
    public void getMsg(@PathVariable String processInstanceId, HttpServletResponse response) throws IOException {
        //http://localhost:9001 可以作为配置项,后期换域名端口生产等都可以直接替换
        String url = "http://localhost:9001/flow/monitor/traceProcess/" + processInstanceId;
        HttpClientUtils.doGetFile(url, response.getOutputStream());

    }

服务方:

    @ApiOperation("流程图进度追踪,已结束标红,运行中标绿")
    @RequestMapping(value = {"/traceProcess/{processInstanceId}"}, method = RequestMethod.GET)
    public void traceprocess(@PathVariable String processInstanceId, HttpServletResponse response) throws IOException {
        activitiTracingChart.generateFlowChart(processInstanceId, response.getOutputStream());
    }
posted @ 2022-06-20 16:23  Rick_Leee  阅读(95)  评论(0)    收藏  举报