zoukankan      html  css  js  c++  java
  • 使用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();
            }
  • 相关阅读:
    MOSS网站与我的网站显示的登录用户信息不同
    Windows Workflow: The Base Activity Library
    非对称加密相关基础
    Windows SharePoint Services 3.0 应用程序模板
    MOSS2007备份还原后搜索服务出现的问题
    MOSS发生“未能转换部分或所有标识引用”错误的处理
    MOSS工作流开发中两个非常实用的类
    MOSS2007最终用户培训资料
    [单调队列] UVA 10534 Wavio Sequence
    [拓扑排序] PKU 1094 Sorting It All Out
  • 原文地址:https://www.cnblogs.com/swbzmx/p/5604373.html
Copyright © 2011-2022 走看看