HttpClient入門get post請求

1.HttpClient入門使用

        注意這個版本主要是基於HttpClient4.5.2版本的來說解的,也是如今最新的版本,之因此要提供版本說明的是由於HttpClient 3版本和HttpClient 4版本差異仍是不少大的,基本HttpClient裏面的接口都變了,你把HttpClient 3版本的代碼拿到HttpClient 4上面都運行不起來,會報錯的。因此這兒必定要注意,好了廢話很少說了,開始。php

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

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

    xml文檔 .xml text/xmljson

    XHTML文檔 .xhtml application/xhtml+xmlapp

    普通文本 .txt text/plainide

    RTF文本 .rtf application/rtfpost

    PDF文檔 .pdf application/pdfui

    Microsoft Word文件 .word application/mswordgoogle

    PNG圖像 .png image/pngurl

    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();

    }
相關文章
相關標籤/搜索