1. 程式人生 > >java 介面自動化之簡單post請求

java 介面自動化之簡單post請求

我們把上一篇沒說的補上。

做介面呢首先要有http協議的基礎。大家請自行學習。不過後續我也會介紹的。

那麼下面是今天的內容。

那麼我們今天來看一下post

 public static void htpost() throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httppost;
		HttpResponse response;
		HttpEntity entity;
		String postResult = null;
		String loginURL="http://192.168.8.241/index.php/Login/prologin";
		httppost = new HttpPost(loginURL); 
                  //建立一個集合用來儲存,post請求需要傳入的引數。
		 List<NameValuePair> formparams1 = new ArrayList<NameValuePair>(); 
		 formparams1.add(new BasicNameValuePair("autologin", "1"));
		 formparams1.add(new BasicNameValuePair("enter", "Sign in"));
		 formparams1.add(new BasicNameValuePair("name", "admin"));
		 formparams1.add(new BasicNameValuePair("password", "123456"));
		 formparams1.add(new BasicNameValuePair("remember", "on"));
		 httppost.setEntity(new UrlEncodedFormEntity(formparams1, "UTF-8"));
		 response = httpClient.execute(httppost);  
         entity = response.getEntity();  
         postResult = EntityUtils.toString(entity, "UTF-8");  
         
         System.out.println("檢視登入介面請求返回的結果:" + postResult); 
         httppost.releaseConnection();  
    }