为了账号安全,请及时绑定邮箱和手机立即绑定

post发送json请求,返回inputstream(用于获取微信小程序二维码)

标签:
Java

1,post发送json请求,返回inputstream(用于获取微信小程序二维码)

 public static InputStream jsonPostToStream(String url, Map<String, Object> param) {
        if (StringUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is required");
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        for (Map.Entry<String, String> entry : getHeaders().entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(JSON.toJSONString(param), "UTF-8");

        httpPost.setEntity(entity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return response.getEntity().getContent();
            } else {
                LOGGER.info("response error! error code {}", response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            LOGGER.info("receive post response error! url {}", url, e);
            try {
                response.close();
                httpClient.close();
            } catch (IOException e1) {
                LOGGER.info("execute post req error!", e1);
            }
        }
        return null;
    }

2,普通get请求

 /**
     * 发送get请求
     *
     * @param url 请求连接
     * @return t
     */
    public static String doGet(String url) {
        LOGGER.error("Get请求url{}:", url);
        if (StringUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is required");
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        for (Map.Entry<String, String> entry : getHeaders().entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }

        //发送请求
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);
            EntityUtils.consume(entity);

            //关闭响应
            response.close();
            return res;
        } catch (IOException e) {
            LOGGER.error("GET请求{}失败, errorStack:", url, e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                LOGGER.error("关闭GET请求Client失败, errorStack:", e);
            }
        }
        return null;
    }

3,发送form-data 表单请求/发送json请求(通过参数isJson进行区分)

 /**
     * 发送post请求
     *
     * @param url   请求的url
     * @param param 参数列表
     * @param <T>   返回值类型
     * @return t
     */
    private static <T> T doPost(String url, Map<String, Object> param, Boolean isJson, Class<T> clazz) {
        if (StringUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is required");
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        for (Map.Entry<String, String> entry : getHeaders().entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }

        if (isJson) {
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            StringEntity entity = new StringEntity(JSON.toJSONString(param), "UTF-8");

            httpPost.setEntity(entity);
        } else {
            List<NameValuePair> form = new ArrayList<>();
            for (Iterator iterator = param.entrySet().iterator(); iterator.hasNext(); ) {
                String name = String.valueOf(iterator.next());
                String value = String.valueOf(param.get(name));
                form.add(new BasicNameValuePair(name, value));
            }

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(form, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                LOGGER.info("form post error!", e);
                return null;
            }
        }

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (isJson) {
                    return JSON.parseObject(EntityUtils.toString(response.getEntity()), clazz);
                }
                return (T) EntityUtils.toString(response.getEntity());
            } else {
                LOGGER.info("response error! error code {}", response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            LOGGER.info("receive post response error! url {}", url, e);
            try {
                response.close();
                httpClient.close();
            } catch (IOException e1) {
                LOGGER.info("execute post req error!", e1);
            }
        }
        return null;
    }
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
11
获赞与收藏
107

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消