itcast-crawler-first(HttpGetParamTest)

package cn.itcast.crawler;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

public class HttpGetParamTest {
    public static void main(String[] args) throws Exception {
        //創建HttpClient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //設置請求地址是 : http://yun.itheima.com/search?keys=Java
        //創建URIBuilder
        URIBuilder uriBuilder = new URIBuilder("http://yun.itheima.com/search");
        //設置參數
        uriBuilder.setParameter("keys","Java");
        //創建HttpGet請求,設置url訪問地址
//        HttpGet httpGet = new HttpGet("http://www.itcast.cn");

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        System.out.println("發起請求的信息: " + httpGet);

        CloseableHttpResponse response = null;
        try {
            //使用HttpClient發起請求,獲取response
            response = httpClient.execute(httpGet);

            //解析響應
            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //關閉response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章