1. 程式人生 > >HttpClient 4.1.3 初學篇---使用Get和Post模擬登入簡單頁面(分別帶引數)

HttpClient 4.1.3 初學篇---使用Get和Post模擬登入簡單頁面(分別帶引數)

    最近需要解決的問題需要用到Httpclient,模擬登陸網站!成功之後就可以用程式碼的方式獲取網站內容或者傳送請求,類似網路爬蟲。

    但是在網上找了好多篇Blog,發現每一片的寫法都不一樣,也糾結了些時間,很納悶,才發現Httpclient版本不一樣。。。現在在這裡說明我使用的版本是HttpClient 4.1.3,我已上傳下載

    看了些Blog,發現直接訪問大型的網站不太容易,於是就自己寫了小的站點,只有一個Servlet,來接受引數(使用者名稱和密碼)就ok了!

這個Servlet就只有get與post方法,而且方法一樣,如下

<span style="font-family:Microsoft YaHei;font-size:14px;">public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String name = request.getParameter("name");
		String psd = request.getParameter("pwd");
		if("wang".equals(name)&&"123".equals(psd)){
			out.print("true");
		}else{
			out.print("false");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		this.doGet(request, response);
	}
</span>
簡單的“伺服器”就搭建好了,接下來就是在客戶端使用Httpclient模擬登入了!

先分析一下想要成功的登入進去的Url是:http://localhost:8080/HttpServer/LoginServlet?name=wang&pwd=123

引數就是兩個("name","wang")和("pwd","123");

接下來就是HttpClent登場了!!!

  • 建立client
<span style="font-family:Microsoft YaHei;font-size:14px;">HttpClient client = new DefaultHttpClient();</span>
  • 選擇傳送請求的方式
<span style="font-family:Microsoft YaHei;font-size:14px;">HttpPost httpPost = new HttpPost(url);								 //傳送請求的方法,此處為Post					
HttpGet httpGet = new HttpGet(url);                                                              //傳送請求的方法,此處為Get</span>
  • 設定引數,Post和Get新增引數的方式不同,下面程式碼有給出
  • 傳送請求
<span style="font-family:Microsoft YaHei;font-size:14px;">       HttpResponse response = client.execute(httpPost); </span>
伺服器收到請求做出的響應和相關Html內容都在response裡,就看怎麼使用了!

下面是程式碼

<span style="font-family:Microsoft YaHei;font-size:14px;">private static void PostMethd() throws UnsupportedEncodingException,
	IOException, ClientProtocolException {
		HttpClient client = new DefaultHttpClient();                         //建立clent
		HttpPost httpPost = new HttpPost(url);								 //傳送請求的方法,此處為Post					
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();     //Post方式新增引數的方法
		formparams.add(new BasicNameValuePair("name",name));
		formparams.add(new BasicNameValuePair("pwd", pwd));
		UrlEncodedFormEntity uefEntity;
		uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");           //防止出現亂碼,加上UTF-8
		httpPost.setEntity(uefEntity);
		HttpResponse response = client.execute(httpPost);                    //提交請求
		InputStream in = PringStatus(response);                              
		in.close();                                                          //關閉輸出流
		client.getConnectionManager().shutdown();                            //關閉client
	}

	

	private static void GetMethd() throws UnsupportedEncodingException,
	IOException, ClientProtocolException {
		HttpClient client = new DefaultHttpClient();                         
		StringBuilder sb = new StringBuilder(url);                           //此處是Get請求,新增引數的方法有點複雜,但我沒有找到好的方法,
		sb.append("?");														 //還請看官拍磚
		sb.append("name=").append(name);
		sb.append("&&");
		sb.append("pwd=").append(pwd);
		
		HttpGet httpGet = new HttpGet(sb.toString());
		HttpResponse response = client.execute(httpGet);
		InputStream in = PringStatus(response);
		in.close();
		client.getConnectionManager().shutdown();
	}
	
	private static InputStream PringStatus(HttpResponse response)
			throws IOException, UnsupportedEncodingException {
		System.out.println(response.getStatusLine().toString());			  //請求傳送之後,伺服器響應的狀態
		InputStream in = response.getEntity().getContent();
		BufferedReader br = new BufferedReader
				(new InputStreamReader(in,"utf-8"));                          
		String line = null;
		while((line = br.readLine())!=null){
			System.out.println(line.toString());
		}
		return in;
	}</span>
好,開啟tomcat,跑起來驗證一下是否成功!
<span style="font-family:Microsoft YaHei;font-size:14px;">HTTP/1.1 200 OK
true
</span>
第一個行是伺服器響應的狀態,第二行則是html內容,因為servlet裡的是
<span style="font-family:Microsoft YaHei;font-size:14px;">out.print("true");</span>

到這裡,HttpClient模擬登入簡單的網站就完成了,接下來我會繼續學習使用HttpClient登入網站,並保留cookie,傳送請求並解析等相關內容!
程式碼下載