使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请输入用户名" />
<EditText
android:id="@+id/et_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请输入密码" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="get"
android:text="get方式提交"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="post"
android:text="post方式提交"
/>
</RelativeLayout>
逻辑代码
MainActivity.java
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
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 android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg){
Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void get(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run(){
final String path = "http://192.168.0.102/web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;
//使用httpClient框架实现get提交
//1.获取httpClient对象
HttpClient hc = new DefaultHttpClient();
//2.创建httpGet对象,参数是网址
HttpGet hg = new HttpGet(path);
//3.使用客户端对象,把get请求发送出去
try {
HttpResponse hr = hc.execute(hg);
//拿到状态行
StatusLine sl = hr.getStatusLine();
if(sl.getStatusCode() == 200){
HttpEntity he = hr.getEntity();
//拿到实体中的内容,是服务器返回的输入流
InputStream is = he.getContent();
String text = Utils.getTextFromStream(is);
//刷新主线程显示text
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
public void post(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run(){
final String path = "http://192.168.0.102/web2/servlet/LoginServlet";
//创建客户端对象
HttpClient hc = new DefaultHttpClient();
//创建post请求对象
HttpPost hp = new HttpPost(path);
//封装form表单提交的数据
BasicNameValuePair bnvp1 = new BasicNameValuePair("name", name);
BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", pass);
//BasicNameValuePair放入集合中
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(bnvp1);
parameters.add(bnvp2);
try {
//把集合传给实体对象
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
//设置post请求对象的额事体,把提交的对象封装在post请求的输出流中
hp.setEntity(entity);
//3.使用客户端发送post请求
HttpResponse hr = hc.execute(hp);
if(hr.getStatusLine().getStatusCode() == 200){
InputStream is = hr.getEntity().getContent();
String text = Utils.getTextFromStream(is);
//刷新主线程显示text
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
}
Utils.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Utils {
public static String getTextFromStream(InputStream is){
byte[] b = new byte[1024];
int len = 0;
//创建字节输出流,读取输入流的文本数据时,同时把数据写入到输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while((len = is.read(b)) != -1){
bos.write(b, 0, len);
}
//把字节数组输出流里面的数据,转换成字节数组
String text = new String(bos.toByteArray());
return text;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}