使用httpclient发送get、post请求

使用httpclient发送get、post请求是最常用的两种web请求
示例代码如下

 1.get请求
    CloseableHttpClient httpclient = HttpClients.createDefault();        
    HttpGet httpGet = new HttpGet("http://targethost/homepage");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);

    // 建立的http连接,仍旧被response1保持着,允许我们从网络socket中获取返回的数据
    // 为了释放资源,我们必须手动消耗掉response1或者取消连接
    //(使用CloseableHttpResponse类的close方法)

    try {
         //response1.getStatusLine();
        //此处可以通过responses获取响应内容,getEntity方法获取响应体。
        HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    2.post 请求
     Post请求关键在于发送参数,参数分为两种:一种是键值对,另一种是纯文本。
     HttpClient 均支持这两种方式:

        HttpPost httpPost = new HttpPost("url");
        // 拼接键值参数
        // List  nvps = new ArrayList ();
        // nvps.add(new BasicNameValuePair("username", "vip"));
        // nvps.add(new BasicNameValuePair("password", "secret"));
        // httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    
        //使用文本参赛
        HttpEntity he = new StringEntity("{"method":"","params":[]}");
        httpPost.setEntity(he);
        httpPost.addHeader("Cookie","AwAAY&dp0gkAIIugIgJOWqoYA");
        httpPost.addHeader("User-Agent", 
            "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0");
        httpPost.addHeader("Host", "www.yahoo.com");

        CloseableHttpResponse response2 = httpclient.execute(httpPost);
        try {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            InputStream is = entity2.getContent();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String content = null;
            while ((content = br.readLine()) != null) {
                int count = StringUtils.countMatches(content, "conversation");
                System.out.println(count);
            }
            br.close();
            // 消耗掉response
            EntityUtils.consume(entity2);
        } finally {
            response2.close();
        }
原文地址:https://www.cnblogs.com/swbzmx/p/5604373.html