码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient发送Post请求,get请求

时间:2017-10-12 19:03:48      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:getc   tac   final   client   seh   tco   ack   nal   stack   

// 创建默认的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请求

标签:getc   tac   final   client   seh   tco   ack   nal   stack   

原文地址:http://www.cnblogs.com/frozenfire/p/7657262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!