1. 程式人生 > >HttpClient get和HttpClient Post請求的方式獲取伺服器的返回資料

HttpClient get和HttpClient Post請求的方式獲取伺服器的返回資料



/*
 * 演示通過HttpClient get請求的方式獲取伺服器的返回資料
 */
public class HttpClientDemo {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		String path="http://10.0.184.105:58080/ServletDemo4/LoginServlet?username=admin&password=admin";
		//1.建立客戶端訪問伺服器的httpclient物件   開啟瀏覽器
		HttpClient httpclient=new DefaultHttpClient();
		//2.以請求的連線地址建立get請求物件     瀏覽器中輸入網址
		HttpGet httpget=new HttpGet(path);
		//3.向伺服器端傳送請求 並且獲取響應物件  瀏覽器中輸入網址點選回車
		HttpResponse response=httpclient.execute(httpget);
		//4.獲取響應物件中的響應碼
		StatusLine statusLine=response.getStatusLine();//獲取請求物件中的響應行物件
		int responseCode=statusLine.getStatusCode();//從狀態行中獲取狀態碼
		if(responseCode==200){
			//5.獲取HttpEntity訊息載體物件  可以接收和傳送訊息
			HttpEntity entity=response.getEntity();
			//EntityUtils中的toString()方法轉換伺服器的響應資料
			String str=EntityUtils.toString(entity, "utf-8");
			System.out.println("伺服器的響應是:"+str);
			
//			//6.從訊息載體物件中獲取操作的讀取流物件
//			InputStream input=entity.getContent();
//			BufferedReader br=new BufferedReader(new InputStreamReader(input));
//			String str=br.readLine();
//			String result=new String(str.getBytes("gbk"), "utf-8");
//			System.out.println("伺服器的響應是:"+result);
//			br.close();
//			input.close();
		}else{
			System.out.println("響應失敗!");
		}
	}


}


/*
 * 演示HttpClient使用Post提交方式提交資料
 * <form action="" method="post">
 *   <input type="text" name="username" value="輸入值">
 *   <input type="password" name="password" value="輸入值">
 * </form>
 * 
 *  username=輸入值   password=輸入值
 */

public class HttpClientDemo4 {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		String baseUrl="http://10.0.184.105:58080/ServletDemo4/LoginServlet";//username=? password=?
		HttpClient httpclient=new DefaultHttpClient();
		//以請求的url地址建立httppost請求物件
		HttpPost httppost=new HttpPost(baseUrl);
		
		//NameValuePair 表示以類的形式儲存提交的鍵值對
		NameValuePair pair1=new BasicNameValuePair("username", "ad");
		NameValuePair pair2=new BasicNameValuePair("password", "admin");
		//集合的目的就是儲存需要向伺服器提交的key-value對的集合
		List<NameValuePair> listPair=new ArrayList<NameValuePair>();
		listPair.add(pair1);
		listPair.add(pair2);
		//HttpEntity 封裝訊息的物件 可以傳送和接受伺服器的訊息  可以通過客戶端請求或者是伺服器端的響應獲取其物件
		HttpEntity entity=new UrlEncodedFormEntity(listPair);//建立httpEntity物件
		httppost.setEntity(entity);//將傳送訊息的載體物件封裝到httppost物件中
		
		HttpResponse response=httpclient.execute(httppost);
		int responseCode=response.getStatusLine().getStatusCode();
		if(responseCode==200){
			//得到伺服器響應的訊息物件
			HttpEntity httpentity=response.getEntity();
			System.out.println("伺服器響應結果是:"+EntityUtils.toString(httpentity, "utf-8"));
		}else{
			System.out.println("響應失敗!");
		}
	}


}