標籤:
下面的Android應用需要向指定頁面發送請求,但該頁面並不是一個簡單的頁面,只有當使用者已經登入,而且登入使用者的使用者名稱是crazyit.org時才可訪問該頁面。如果使用HTTPURLConnection來訪問該頁面,那麼需要處理的細節就太複雜了。
訪問Web應用中被保護的頁面,如果使用瀏覽器則十分簡單,使用者通過系統提供的登入頁面登入系統,瀏覽器會負責維護與伺服器之間的Session,如果使用者登入的使用者名稱、密碼符合要求,就可以訪問被保護資源了。
為了通過HttpClient來訪問被保護頁面,程式同樣需要使用HttpClient來登入系統,只要應用程式使用同一個HttpClient發送請求,HttpClient會自動維護與伺服器之間的Session狀態,也就是說程式第一次使用HttpClient登入系統後,接下來使用HttpClient即可訪問被保護的頁面了。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class HttpClientTest extends Activity {
Button get;
Button login;
EditText response;
HttpClient httpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_client_test);
//建立DefaultHttpClient對象
httpClient = new DefaultHttpClient();
get = (Button) findViewById(R.id.get);
login = (Button) findViewById(R.id.login);
response = (EditText) findViewById(R.id.response);
get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 建立一個HttpGet對象
HttpGet get = new HttpGet("http://172.18.5.198:8080/foo/secret.jsp");
try {
//發送GET請求
HttpResponse httpResponse = httpClient.execute(get);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
//讀取伺服器響應
BufferedReader br = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line = null;
while((line = br.readLine()) != null){
//使用response文字框顯示伺服器響應
response.append(line + "\n");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final View loginDialog = getLayoutInflater()
.inflate(R.layout.login, null);
new AlertDialog.Builder(HttpClientTest.this)
.setTitle("登入系統")
.setView(loginDialog)
.setPositiveButton("登入", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = ((EditText)loginDialog.findViewById(
R.id.username)).getText().toString();
String pass = ((EditText)loginDialog.findViewById(
R.id.password)).getText().toString();
HttpPost post = new HttpPost("http://172.18.5.198:8080/foo/login.jsp");
//如果傳遞參數個數比較多可以對傳遞的參數進行封裝
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("pass", pass));
try {
//佈建要求參數
post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//發送POST請求
HttpResponse response = httpClient.execute(post);
//如果伺服器成功地返迴響應
if(response.getStatusLine().getStatusCode() == 200){
String msg = EntityUtils.toString(response.getEntity());
//提示登陸成功
Toast.makeText(HttpClientTest.this, msg, 5000).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).setNegativeButton("取消", null).show();
}
});
}
}
使用HttpClient訪問被保護資源