1. 程式人生 > >HttpClient傳送請求,get和post兩種方式,分別帶引數和不帶引數

HttpClient傳送請求,get和post兩種方式,分別帶引數和不帶引數

(一)、匯入HttpCLient的jar包

  <dependencies>
	  	<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.6</version>
		</dependency>
  </dependencies>

(二)程式碼實現

1、httpCLient傳送get請求(帶引數直接在ulr後跟引數即可)

	public void HttpClientGet() throws Exception {
		// 獲取http客戶端
		CloseableHttpClient client = HttpClients.createDefault();
		// 通過httpget方式來實現我們的get請求
		HttpGet httpGet = new HttpGet("http://www.itcast.cn?username=zhangsan&password=lisi");
		// 通過client呼叫execute方法,得到我們的執行結果就是一個response,所有的資料都封裝在response裡面了
		CloseableHttpResponse Response = client.execute(httpGet);
		// HttpEntity
		// 是一箇中間的橋樑,在httpClient裡面,是連線我們的請求與響應的一箇中間橋樑,所有的請求引數都是通過HttpEntity攜帶過去的
		// 所有的響應的資料,也全部都是封裝在HttpEntity裡面
		HttpEntity entity = Response.getEntity();
		// 通過EntityUtils 來將我們的資料轉換成字串
		String str = EntityUtils.toString(entity, "UTF-8");
		// EntityUtils.toString(entity)
		System.out.println(str);
		// 關閉
		Response.close();
	}

2、httpCLient傳送post請求(帶引數見其中程式碼)

	public void HttpClientPost() throws Exception {
		// 獲取預設的請求客戶端
		CloseableHttpClient client = HttpClients.createDefault();
		// 通過HttpPost來發送post請求
		HttpPost httpPost = new HttpPost("http://www.itcast.cn");
		/*
		 * post帶引數開始
		 */
		// 第三步:構造list集合,往裡面丟資料
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		BasicNameValuePair basicNameValuePair = new BasicNameValuePair("username", "zhangsan");
		BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("password", "123456");
		list.add(basicNameValuePair);
		list.add(basicNameValuePair2);
		// 第二步:我們發現Entity是一個介面,所以只能找實現類,發現實現類又需要一個集合,集合的泛型是NameValuePair型別
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
		// 第一步:通過setEntity 將我們的entity物件傳遞過去
		httpPost.setEntity(formEntity);
		/*
		 * post帶引數結束
		 */
		// HttpEntity
		// 是一箇中間的橋樑,在httpClient裡面,是連線我們的請求與響應的一箇中間橋樑,所有的請求引數都是通過HttpEntity攜帶過去的
		// 通過client來執行請求,獲取一個響應結果
		CloseableHttpResponse response = client.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String str = EntityUtils.toString(entity, "UTF-8");
		System.out.println(str);
		// 關閉
		response.close();
	}