HttpClient的簡單使用

奮鬥的小青年_發表於2017-07-30

HttpClient簡介

HttpClient 是 Apache Jakarta Common 下的子專案,用來提供高效的、最新的、功能豐富的支援 HTTP 協議的客戶端程式設計工具包。

GET請求

       @Test
	public void testGet() throws Exception{
		//建立一個httpclient物件
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//建立一個uri物件
		URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com ");
		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();
	}	

POST請求

	@Test
	public void testPost() throws Exception{
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
		//建立一個post物件
		HttpPost post = new HttpPost("http://localhost:8080/httpclient/testpost.html");
		//建立一個Entity。模擬一個表單
		List<NameValuePair> kvList = new ArrayList<>();
		kvList.add(new BasicNameValuePair("username", "haha"));
		kvList.add(new BasicNameValuePair("password", "123456"));
		
		//包裝成一個Entity物件
		StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");
		//設定請求的內容
		post.setEntity(entity);
		
		//執行post請求
		CloseableHttpResponse response = httpClient.execute(post);
		String string = EntityUtils.toString(response.getEntity());
		System.out.println(string);
		response.close();
		httpClient.close();
	}	

相關文章