1. 程式人生 > >HttpClient Post提交 帶引數

HttpClient Post提交 帶引數

/*
	 * HttpClient Post提交 帶引數
	 */
	@Test
	public void fun4() throws ClientProtocolException, IOException{
		//1、建立HttpClient
		CloseableHttpClient clients = HttpClients.createDefault();
		//2、封裝請求引數
		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("username", "cgx"));
		list.add(new BasicNameValuePair("password", "123456"));
		
		//3、轉化引數
		UrlEncodedFormEntity refe = new UrlEncodedFormEntity(list,Consts.UTF_8);
		
		//4、建立HttpPost
		HttpPost post = new HttpPost("http://localhost:8080/itcast297/loginAction_login");
		
		//5、設定引數
		post.setEntity(refe);
		//3、執行請求
		CloseableHttpResponse response = clients.execute(post);
		
		//4獲取實體
		HttpEntity entity = response.getEntity();
		
		//將實體轉換成字串
		System.out.println(EntityUtils.toString(entity));
		
		response.close();
		
	}