第二十章之HttpClient请求

Http工作的大致原理:

①客户端连接到Web服务器

②发送HTTP请求

③服务器接受请求并返回HTTP响应

④释放连接TCP连接

⑤客户端浏览器解析HTML内容

⑥客户端与服务端断开连接


步骤:

①创建一个类继承Thread

List<NameValuePair> parameters=new ArrayList<NameValuePair>();

parameters.add(new BasicNameValuePair("name","张三"));

②创建HttpClien请求执行t实例 HttpClient client=new DefaultHttpClient();

③设置请求方式

HttpPost request=new HttpPost("..................");

④绑定参数

UrlEncodedFormEntity entity=new UrlEncodedFormEntity(parameters);

将绑定的参数设置到请求对象当中

request.setEntity(entity);

HttpResponse response=client.excute(request);


if(response.getStatusLine().getStatusCode() == 200){
//获取服务器端的数据
String str = EntityUtils.toString(response.getEntity());
//从消息池中获取消息对象。
Message msg = handler.obtainMessage();
//创建数据存放对象
Bundle bundle = new Bundle();
bundle.putString("name", str);
//把数据对象放到消息对象当中
msg.setData(bundle);
//将消息对象发送到消息队列
handler.sendMessage(msg);
}


上课案例

MainActivity.java

package com.ryan.lsn3_18;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	Button start_btn;
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			//获取子线程传递来的数据
			Bundle bundle = msg.getData();
			//根据键获取值
			String name = bundle.getString("name");
			//更新按钮的文本
			start_btn.setText(name);
			super.handleMessage(msg);
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initView();
	}
	public void initView(){
		start_btn = (Button)findViewById(R.id.start_btn);
		start_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				MyThread thread = new MyThread();
				//启动 线程
//				thread.start();
				//创建线程对象
				DemoThread thread = new DemoThread();
				//启动线程
				thread.start();
			}
		});
	}
	class DemoThread extends Thread{

		@Override
		public void run() {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			parameters.add(new BasicNameValuePair("name", "张三"));
			parameters.add(new BasicNameValuePair("password", "123456"));
			try {
				//请求执行对象
				HttpClient client = new DefaultHttpClient();
				//设置请求方式
				HttpPost request = new HttpPost("http://10.0.2.2:8080/MyServer/DemoServlet");
				//绑定参数
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
				//将绑定的参数设置到请求对象当中
				request.setEntity(entity);
				//执行请求
				HttpResponse response = client.execute(request);
				//判断连接是否成功,连接成功为200
				if(response.getStatusLine().getStatusCode() == 200){
					//获取服务器端的数据
					String str = EntityUtils.toString(response.getEntity());
					//从消息池中获取消息对象。
					Message msg = handler.obtainMessage();
					//创建数据存放对象
					Bundle bundle = new Bundle();
					bundle.putString("name", str);
					//把数据对象放到消息对象当中
					msg.setData(bundle);
					//将消息对象发送到消息队列
					handler.sendMessage(msg);
				}
				
				
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	
	class MyThread extends Thread{
		@Override
		public void run() {
			try {
				String stu = "";
				//构造请求地址
				URL url = new URL("http://10.0.2.2:8080/MyServer/DemoServlet");
				//打开连接
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				//设置服务器可读
				conn.setDoInput(true);
				//设置连接超时
				conn.setConnectTimeout(5000);
				//设置请求方式
				conn.setRequestMethod("POST");
				//请求连接
				conn.connect();
				//判断是否连接成狗
				if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
					//获取服务器端的输入流
					InputStream is = conn.getInputStream();
					//读取服务器端的数据
					byte []buffer = new byte[1024];
					int length =0;
					while((length = is.read(buffer)) != -1){
						stu = new String(buffer, 0, length);
					}
				}
				
				//从消息池中获取消息对象。
				Message msg = handler.obtainMessage();
				//创建数据存放对象
				Bundle bundle = new Bundle();
				bundle.putString("name", stu);
				//把数据对象放到消息对象当中
				msg.setData(bundle);
				//将消息对象发送到消息队列
				handler.sendMessage(msg);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值