BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream())); String data = ""; String line = ""; while ((line = br.readLine()) != null) { data = data + line; } return data; } } 接下來就是使用HttpClient,代碼類似的,我做了相同的實驗,結果就直接出來了,HttpClient會自動的管理Session,第二次請求不需要手動去設置Session就可以登錄上。復制代碼 代碼如下: public class NetClient {
private HttpClient client = null;
public NetClient() { client = new DefaultHttpClient(); }
public String request(String url) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(url); HttpResponse res = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); String data = ""; String line = ""; while ((line = br.readLine()) != null) { data = data + line; } return data; }
public String login(String url) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(url);
//設置post參數的方式還真是不人性化啊…… ArrayList NameValuePair pa = new ArrayList NameValuePair pa.add( new BasicNameValuePair( "username", "admin")); pa.add( new BasicNameValuePair( "password", "admin")); post.setEntity( new UrlEncodedFormEntity(pa, "UTF-8")); HttpResponse res = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); String data = ""; String line = ""; while ((line = br.readLine()) != null) { data = data + line; } return data; } } 最后總結一下,Session驗證的方式是在一次會話中,為每一個客戶端都生成了一個SESSIONID,如果是成功登陸的,服務器端就會記錄好,登陸成功的SESSIONID,如果登陸失敗或者新的SESSIONID,都將無法驗證登陸,這就是SESSION驗證登陸的基本情況。而HttpURLConnection和HttpClient這兩個類都可以用來網絡請求,但稍有不同,HttpuRLConnection每一次請求都是新的會話,如果需要去驗證SESSIONID,就必須手動的去設置Header,HttpClient就能智能的管理Session,不需要手動設置,實際上HttpClint就類似于一個程序中的小瀏覽器。最大的槽點我覺得就是這兩個類設置post參數的方式都很2B一點都不方便……另外HttpClient不能同時發送兩次請求,如果一個請求還沒有結束或者關閉,又馬上開啟另一個請求。就會報警告,截個圖吧