使用Apache httpclient

主界面一个访问页面按钮,一个登陆系统按钮,一个巨大的edittext,用来显示服务器的响应内容

如果没有登录,点击访问页面按钮会显示“您没有被授权访问该页面”。如果已经登陆,会在edittext中显示服务器的响应结果

发送请求的步骤:

1.创建HttpClient对象

2.如果发送GET请求,创建HttpGet对象,如果发送POST请求,创建HttpPost对象

3.调用HttpClient对象的execute()方法发送请求,执行该方法返回一个HttpResponse。

4.HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。

 

访问页面按钮的监听函数

HttpGet get = new HttpGet("http://222.18.174.132:8080/foo/secret.jsp");
    try
    {
     //发送get请求

     //httpClient对象的execute方法返回一个HttpResponse
     HttpResponse httpResponse = httpClient.execute(get);

     //httpResponse的getEntity方法获取的对象中,包装了服务器的响应内容
     HttpEntity entity = httpResponse.getEntity();
     if(entity != null)
     {
      //读取服务器响应
      BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
      String line = null;
      while((line = br.readLine())!= null)
      {
       //使用response文本框显示服务器响应
       response.append(line + "\n");
      }
     }
    }

 

登录系统按钮的监听函数

getLayoutinflate.inflate方法得到我们要显示的xml文件,再用builder.setView方法将取出来的xml文件装载进对话框中

final View loginDialog = getLayoutInflater().inflate(R.layout.login, null);
    new AlertDialog.Builder(httpclient.this)
    .setTitle("登陆系统")
    .setView(loginDialog)
    .setPositiveButton("登陆", new DialogInterface.OnClickListener() {
     //嵌套着登陆按钮的监听函数
     public void onClick(DialogInterface arg0, int arg1) {
      String name = ((EditText)loginDialog.findViewById(R.id.name)).getText().toString();
      String pass = ((EditText)loginDialog.findViewById(R.id.pass)).getText().toString();
      HttpPost post = new HttpPost("http://222.18.174.132:8080/foo/login.jsp");
      //如果传递参数的个数比较多可以对传递的参数进行封装
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("name", name));
      params.add(new BasicNameValuePair("pass", pass));
      try
      {
       //设置请求参数
       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());
        //提示登陆成功
        Toast.makeText(httpclient.this, msg, 5000).show();
       }
      }
      catch(Exception e)
      {
       e.printStackTrace();
      }
     }
    }).setNegativeButton("取消", null).show();

 

用户名是crazyit.org  密码是leegang

记得去注册访问网络的权限

使用Apache <wbr>httpclient

使用Apache <wbr>httpclient

代码

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值