HttpClient入門get post請求


1.HttpClient入門使用

        注意這個版本主要是基於HttpClient4.5.2版本的來講解的,也是現在最新的版本,之所以要提供版本說明的是因為HttpClient 3版本和HttpClient 4版本差別還是很多大的,基本HttpClient里面的接口都變了,你把HttpClient 3版本的代碼拿到HttpClient 4上面都運行不起來,會報錯的。所以這兒一定要注意,好了廢話不多說了,開始。

2.在pom.xml加入對httpclient的必需的jar包的依賴

<!--httpclient依賴包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.2</version>
</dependency>

注意:常見的MIME類型(通用型):

    超文本標記語言文本 .html text/html

    xml文檔 .xml text/xml

    XHTML文檔 .xhtml application/xhtml+xml

    普通文本 .txt text/plain

    RTF文本 .rtf application/rtf

    PDF文檔 .pdf application/pdf

    Microsoft Word文件 .word application/msword

    PNG圖像 .png image/png

    GIF圖形 .gif image/gif

    JPEG圖形 .jpeg,.jpg image/jpeg

    au聲音文件 .au audio/basic

    MIDI音樂文件 mid,.midi audio/midi,audio/x-midi

    RealAudio音樂文件 .ra, .ram audio/x-pn-realaudio

    MPEG文件 .mpg,.mpeg video/mpeg

    AVI文件 .avi video/x-msvideo

    GZIP文件 .gz application/x-gzip

    TAR文件 .tar application/x-tar

    任意的二進制數據 application/octet-stream

3.抓取網頁的內容並打印到控制台的demo--get請求

    @Test
    public void testHttpClientA() throws IOException {
        //使用默認配置的httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //即將訪問的url
        String url = "http://www.baidu.com";
        //get形式的訪問
        HttpGet httpGet = new HttpGet(url);

        //執行請求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            //打印請求的狀態碼  請求成功為200
            System.out.println(response.getStatusLine().getStatusCode());
            //打印請求的實體內容 返回json格式
            HttpEntity entity = response.getEntity();
            //獲取所有頭信息
            Header[] allHeaders = response.getAllHeaders();
            for (Header allHeader : allHeaders) {
                System.out.println(allHeader.getName());
                System.out.println(allHeader.getValue());
                System.out.println(allHeader.toString());
            }

            //方法一 官方不推薦
            if (entity != null) {
                //輸出更詳細的抓取內容(html格式)
              System.out.println(EntityUtils.toString(entity,"utf-8"));
            }
            //釋放資源
            EntityUtils.consume(entity);
            //方法二 官方推薦 使用流的形式處理請求結果
      /*  if (entity != null) {
            InputStream content = entity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(content));
            String line = "";
            while ((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            }
            bufferedReader.close();
        }*/
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();
        }

4.帶參數的請求--get請求

    @Test
    public void testHttpClientB() throws URISyntaxException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URI uri = new URIBuilder()
                .setScheme("http")
                .setHost("www.google.com")
                .setPath("/search")
                .setParameter("q", "httpclient")
                .setParameter("btnG", "Google搜索")
                .setParameter("aq", "f")
                .setParameter("oq", "dd")
                .build();
        HttpGet httpGet = new HttpGet(uri);
        System.out.println(httpGet.getURI());

    }

5.帶參數的請求--post請求

    @Test
    public void testHttpClientPost() throws IOException {
        //定義uri
        String uri="http://php.weather.sina.com.cn/iframe/index/w_cl.php";
        //需要傳入的參數
        Map<String, String> map = new HashMap<String, String>();
        map.put("code", "js");
        map.put("day", "0");
        map.put("city", "上海");
        map.put("dfc", "1");
        map.put("charset", "utf-8");
        String encoding = "utf-8";
        //創建默認的httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //創建post請求對象
        HttpPost httpPost = new HttpPost(uri);
        //裝填請求參數
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        //設置參數到請求對象中
        httpPost.setEntity(new UrlEncodedFormEntity(list,encoding));

        System.out.println("請求地址:"+uri);
        System.out.println("請求參數:"+list.toString());

        //設置header信息
        //指定報文頭【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //執行請求操作,並拿到結果(同步阻塞)
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //獲取所有的請求頭信息
        Header[] allHeaders = response.getAllHeaders();
        for (Header allHeader : allHeaders) {
            System.out.println(allHeader.toString());
        }
        //獲取結果實體
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            System.out.println(EntityUtils.toString(entity,encoding));
        }
     //關流
        EntityUtils.consume(entity);
        response.close();

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM