1. 程式人生 > >httpclient 簡單例項

httpclient 簡單例項

使用httpclient執行get請求

@Test
	public void doGet() throws Exception {
		//建立一個httpclient物件
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//建立一個GET物件
		HttpGet get = new HttpGet("http://www.sogou.com");
		//執行請求
		CloseableHttpResponse response = httpClient.execute(get);
		//取響應的結果
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println(statusCode);
		HttpEntity entity = response.getEntity();
		String string = EntityUtils.toString(entity, "utf-8");
		System.out.println(string);
		//關閉httpclient
		response.close();
		httpClient.close();
	}

   執行get請求帶引數

@Test
	public void doGetWithParam() throws Exception{
		//建立一個httpclient物件
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//建立一個uri物件
		URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
		uriBuilder.addParameter("query", "花千骨");
		HttpGet get = new HttpGet(uriBuilder.build());
		//執行請求
		CloseableHttpResponse response = httpClient.execute(get);
		//取響應的結果
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println(statusCode);
		HttpEntity entity = response.getEntity();
		String string = EntityUtils.toString(entity, "utf-8");
		System.out.println(string);
		//關閉httpclient
		response.close();
		httpClient.close();
	}