HttpClient的get和post请求数据

在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的API我们可以很方便的发出GET,POST请求。

一,使用HtttpClient的GET方法需要以下6个步骤:

1,创建HtttpClient的实例

2,创建某种连接方法的实例,这里是HttpGet,在HttpGet的构造函数中传入待连接的地址

3,调用第一步中创建好的实例的execute方法来执行第二步中创建好的get实例

4,第三步返回的是HttpResponse,解析HttpResponse

5,释放连接

6,对得到的内容进行处理

二,根据以上步骤,我们来编写用GET方法来取得某网页内容的代码。

1,布局文件:

<span style="font-size:14px;"><LinearLayout 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:orientation="vertical" >

<EditText 
        android:id="@+id/ed_name"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_marginTop="10dp"/>

    <EditText 
        android:id="@+id/ed_pass"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"
        android:inputType="phone"/>


    <Button 
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_marginTop="15dp"
        android:onClick="doClick"
        android:text="登录"
        android:textSize="20sp"/>
</LinearLayout></span>

2,实现具体功能的java类:

<span style="font-size:14px;">public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
//Handler调用handleMessage方法来更新UI
Handler handler = new Handler(){
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
}
};
public void doClick(View v) {
//重开一个线程处理耗时操作
Thread thread = new Thread() {
public void run() {
EditText ed_name = (EditText) findViewById(R.id.ed_name);
EditText ed_pass = (EditText) findViewById(R.id.ed_pass);
//获取用户输入的用户名和密码
String name = ed_name.getText().toString().trim();
String pass = ed_pass.getText().toString().trim();
//访问服务器路径,URLEncoder用来解决编码问题
String url = "http://localhost:8080/Web?name="+URLEncoder.encode(name)+"&pass="+pass;
// 1,创建HttpClient对象
HttpClient client = new DefaultHttpClient();
// 2,创建HttpGet请求对象
HttpGet get = new HttpGet(url);
try {
// 3,用HttpClient发送get请求,返回服务器给客户端的响应
HttpResponse response = client.execute(get);
// 4,获取状态行对象
StatusLine sl = response.getStatusLine();
// 5,通过状态行对象来获取状态码,如果是200,说明请求成功
if (sl.getStatusCode() == 200) {
// 6,获取HttpEntity对象
HttpEntity entity = response.getEntity();
// 7,通过Entity实体来获取服务器端返回的数据
InputStream is = entity.getContent();
// 8,通过封装好的方法来转换数据
String text = Utils.getTextFromStream(is);
//9,把消息传给主线程进行UI更新
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}

//用来转换数据的流工具

public  static String  getTextFromStream(InputStream  is){

int len = 0;
byte [] buffer = new byte[1024];
//定义一个字节数组输出流,保存每次读取到的字节
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while ((len=is.read(buffer))!=-1) {
bos.write(buffer,0,len);
}
//使用哪个码表来构造这个字符串
String text = new String(bos.toByteArray());
return text;
} catch (Exception e) {
}
return null;
}
}</span>

三,通过post方法请求:

1,布局代码和get方法的一样,这里不再冗余。

2,实现类中的java代码:

<span style="font-size:14px;">public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
}
};
public void doClick(View v) {
Thread thread = new Thread() {
public void run() {
EditText ed_name = (EditText) findViewById(R.id.ed_name);
EditText ed_pass = (EditText) findViewById(R.id.ed_pass);
// 获取用户输入的用户名和密码
String name = ed_name.getText().toString().trim();
String pass = ed_pass.getText().toString().trim();
// 访问服务器路径
String url = "http://localhost:8080/Web";
// 声明HttpClient对象
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost();
try {
//通过post提交的数据放在Entity中
List<NameValuePair>Parameters = new ArrayList<NameValuePair>();

 //NameValuePair是接口,不能直接使用,要用其子类BasicNameValuePair  来实现其功能
BasicNameValuePair  pair1 = new BasicNameValuePair("name", name);
BasicNameValuePair  pair2 = new BasicNameValuePair("pass", pass);
Parameters.add(pair1);
Parameters.add(pair2);

UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(Parameters,"utf-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
//判断响应码
if (response.getStatusLine().getStatusCode()==200) {
InputStream is = response.getEntity().getContent();
String text = Utils .getTextFromStream(is);
//把消息发送到主线程进行UI更新
Message msg = new Message();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
} 
}
};
thread.start();
}


//用来转换数据的工具流

public  static String  getTextFromStream(InputStream  is){
int len = 0;
byte [] buffer = new byte[1024];
//定义一个字节数组输出流,保存每次读取到的字节
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while ((len=is.read(buffer))!=-1) {
bos.write(buffer,0,len);
}
//使用哪个码表来构造这个字符串
String text = new String(bos.toByteArray());
return text;
} catch (Exception e) {
}
return null;
}<span style="font-family: arial, sans-serif; line-height: 24px; text-indent: 2em;">}</span></span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值