爲了更好的處理向web站點的請求,包括處理Session ,Cookie等細節問題,Apache 開源組織提供了一個 HttpClient項目.它是一個簡單的HTTP客戶端(並不是瀏覽器),可以用於發送HTTP請求,接受HTTP響應,.但不會緩存服務器的響應,不能執行HTML頁面中嵌入的JavaScript代碼,也不會對頁面內容進行任何解析,處理.
使用 HttpClient 發送請求,接受響應. 需要如下幾步:
- 創建 HttpClient 對象.
- 如需要發送GET 請求,則創建 HttpGet對象.如發動POST請求,則創建HttpPost對象.
- 如果需要發送請求參數,可調用 HttpGet,HttpPost共同的 setParams(HttpParams params) 方法來添加請求參數; 對於 HttpPost 對象而言, 也可調用setEntity(HttpEntity entity)方法來設置請求參數.
- 調用 HttpClient 對象的execute(HttpUriRequest request) 發送請求執行該方法返回一個HttpResponse.
- 調用 HttpResponse 的getAllHeaders(), getHeaders(String name),等方法獲取服務器的響應頭; 調用 HttpResponse 的getEntity()方法可獲取 HttpEntity 對象,該對象包裝了服務器的響應內容.程序可通過該對象獲取服務器的響應內容.
package com.net.httpclient;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* 使用 Apache HttpClient
* org.apache.http.client.HttpClient
*/
public class HttpClientActivity extends AppCompatActivity {
TextView respone;
Button assess, login;
HttpClient httpClient;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 0x1234)
{
// 使用response文本框顯示服務器響應
respone.append(msg.obj.toString() + "\n");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_client);
//創建 DefaultHttpClient 對象
httpClient = new DefaultHttpClient();
respone = (TextView) findViewById(R.id.response);
assess = (Button) findViewById(R.id.accessSecret);
login = (Button) findViewById(R.id.showLogin);
initListener();
}
private void initListener() {
assess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
super.run();
//創建一個 HttpGet 對象
HttpGet get = new HttpGet("http://169.254.214.117: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) {
Message msg = Message.obtain();
msg.what = 0x1234;
msg.obj = line;
mHandler.sendMessage(msg);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//加載登錄界面
final View loginDialog = getLayoutInflater().inflate(R.layout.login, null);
//使用對話框供用戶登錄
new AlertDialog.Builder(HttpClientActivity.this)
.setTitle("登錄系統")
.setView(loginDialog)
.setPositiveButton("登錄", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//獲取用戶輸入的用戶名, 密碼
final String name = ((EditText) loginDialog.findViewById(R.id.name)).getText().toString();
final String pass = ((EditText) loginDialog.findViewById(R.id.pass)).getText().toString();
//開啓子線程
new Thread() {
@Override
public void run() {
try {
HttpPost post = new HttpPost("http://169.254.214.117:8080/foo/login.jsp");
//如果傳遞參數個數比較多,可以對傳遞的多個參數進行封裝
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("pass", pass));
//設置請求參數
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());
Looper.prepare();
//提示登錄成功
Toast.makeText(HttpClientActivity.this, msg, Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}).setNegativeButton("取消",null).show();
}
});
}
}