Java HttpClient 4.x的用法(Get篇)

HttpClient是一个经典的Java的HTTP客户端,当升级到4.x后,其API发生了很大变化,下面以带参数的HTTP Get为例,说说如何使用。

		// Timeout Stradegy
		RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig.custom()
				.setSocketTimeout(1000).setConnectTimeout(1000).build();

		// Create client
		CloseableHttpClient httpclient = HttpClients
				.custom()
				.setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
				.setKeepAliveStrategy(
						DefaultConnectionKeepAliveStrategy.INSTANCE).build();

		HttpGet get = new HttpGet("http://www.baidu.com");
		URIBuilder uriBuilder = new URIBuilder(get.getURI()).setParameter("wd",
				"度娘");
		get.setURI(uriBuilder.build());

		// Execute & Get response
		CloseableHttpResponse resp = httpclient.execute(get);
		System.out.println(resp.getStatusLine().getStatusCode());
		System.out.println(IOUtils.toString(resp.getEntity().getContent()));

 

Leave a Reply

Your email address will not be published. Required fields are marked *