HttpClient发送Post请求,get请求

Posted 吾乃闪耀的知识灯塔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient发送Post请求,get请求相关的知识,希望对你有一定的参考价值。

// 创建默认的httpclient实例
        CloseableHttpClient httpclient = getHttpClient();
        CloseableHttpResponse response = null;
        // 创建httpPost
        HttpPost httpPost = new HttpPost("url地址");
httpPost.setHeader(HTTP.CONTENT_TYPE,
"application/json; charset=utf-8"); try { StringEntity param = new StringEntity(params, ContentType.APPLICATION_JSON); httpPost.setEntity(param); response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if(entity != null){ InputStream is = entity.getContent(); } } catch (Exception e) { LOG.error("sendPostRequest error:", e); } finally { try { //关闭连接,释放资源 response.close(); httpclient.close(); } catch (Exception e) { LOG.error("HttpClient close error:", e); } }

发送Get请求

CloseableHttpClient httpclient = getHttpClient();
        CloseableHttpResponse response = null;
        HttpGet httpget = new HttpGet("url地址");
        try {
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                InputStream is = entity.getContent();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭连接,释放资源
                response.close();
                closeHttpClient(httpclient);
            } catch (Exception e) {
                LOG.error("HttpClient close error:", e);
            }
        }

借用某位大神的代码,只为日后方便查阅,请勿介意。

读书人的事情怎么能叫偷,那叫窃!

以上是关于HttpClient发送Post请求,get请求的主要内容,如果未能解决你的问题,请参考以下文章

HttpClient发送get,post接口请求

HttpClient模拟get,post请求并发送请求参数(json等)

为啥 HttpClient.PostAsync 似乎将请求作为 GET 而不是 POST 发送?

后台发送请求,HttpClient的post,get各种请求,带header的请求

httpclient就是个能发送http连接的工具包,包括能发送post请求和get请求

用java做一个httpClient 发送https 的get请求,需要证书验证的那种,求大神指点一下!