为了更好的处理向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();
}
});
}
}