Android网络编程使用HttpClient访问web站点

HttpClientDemo.java界面就是两个按钮和一个文本框

/*
 * 用HttpClientlai 来访问提交请求,接收响应
 * A,发送GET请求
 * 1,创建HttpClient对象;HttpClient httpclient=new DefaultHttpClient();
 * 2,发送GET请求,创建HttpGet对象:HttpGet httpget=new HttpGet("http://www.baidu.com");
 * 3,用HttpClient对象实行HttpGet对象会得到服务器响应对象HttpResponse的对象,响应就封装在HttpResponse中:
 *  HttpResponse httpresponse=httpclient.execute(httpget);
 * 4,从httpresponse响应中获得Http实例
		HttpEntity entity=httpresponse.getEntity(); 
 * */
public class HttpClientDemo extends Activity {
   TextView response;
   //声明HttpClient对象
   HttpClient httpclient;
   Handler handler=new Handler(){
	  public void handleMessage(Message msg){
		  if(msg.what==0x123){
			//  使用response显示服务器的响应
			  response.append(msg.obj.toString()+"\n");
		  }
	  }
   };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_client);
        //1,创建DefaultHttpClient对象,接口回调HttpClient是个接口
        httpclient=new DefaultHttpClient();
        response=(TextView) findViewById(R.id.response);
    }
    /*
     * 向服务发送GET请求流程
     * 
     * */
    public void accessSecret(View v){
    	response.setText("");
    	//点击按钮,开启线程,在线程中发送Get请求
    	new Thread(){
    		public void run(){
    			//2,创建一个HttpGet对象
    			HttpGet httpget=new HttpGet("http://localhost:8080/foo/secret.jsp");//jsp部署在To吗cat服务器上
    			try {
    				    //3,用HttpClient对象实行HttpGet对象会得到服务器响应对象HttpResponse的对象,响应就封装在HttpResponse中
					    HttpResponse httpresponse=httpclient.execute(httpget);
					    //4,从httpresponse响应中获得Http实例
					    HttpEntity entity=httpresponse.getEntity();
					    if(entity!=null){
					    	//5,entity实例中获得内容,建立输入流,读取服务器内容
					    	BufferedReader br=new BufferedReader(new InputStreamReader(entity.getContent()));
					    	String line=null;
					    	while((line=br.readLine())!=null){//循环从输入流中读取内容
					    		Message msg=new Message();
					    		msg.what=0x123;
					    		msg.obj=line;
					    	    handler.sendMessage(msg);//发给UI线程更新UI组件
					    	}
					    }
					    
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    			
    		}
    	}.start();
    }
    /*
     * 发送Post请求流程
     * 
     * 
     * */
   public void showLogin(View v){
	   final View loginDialog=getLayoutInflater().inflate(R.layout.login, null);
	   new AlertDialog.Builder(HttpClientDemo.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();
				//点击确定,开启线程,在线程中发送Post请求
				new Thread(){
					public void run(){													
							try {
								//2,创建HttpPost对象
								HttpPost httppost=new HttpPost("http://localhost:8080/foo/login.jsp");//jsp部署在To吗cat服务器上
								//3,对传递的参数进行封装,NameValuePair是简单名称值对节点类型
								List<NameValuePair> params=new ArrayList<NameValuePair>();
								params.add(new BasicNameValuePair("name",name));//添加参数
								params.add(new BasicNameValuePair("pass",pass));
								//3,设置编码
								httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
								//4,HttpClient对象执行HttpPost请求,获得相应
								HttpResponse httpresponse=httpclient.execute(httppost);
								//5,如果状态码是200就表示服务器成功相应
								if(httpresponse.getStatusLine().getStatusCode()==200){
									//200:响应成功,301/302:重定向,404:not found未找到资源 ,501服务器遇到错误,使其无法对请求提供服务
									String msg = EntityUtils.toString(httpresponse.getEntity());								
									Looper.prepare();
									//提示登录成功
									Toast.makeText(HttpClientDemo.this, msg, Toast.LENGTH_LONG).show();
									Looper.loop();
								}
							} catch (ParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}																			
					}
				}.start();
				
			}
	       }).setNegativeButton("取消", null).show();

    
}



你可能感兴趣的:(httpclient,网络编程,HttpPost,HttpGet,HttpResponse)