使用Apache httpclient

来源:互联网 发布:蝴蝶机夹胸 知乎 编辑:程序博客网 时间:2024/05/29 19:12

主界面一个访问页面按钮,一个登陆系统按钮,一个巨大的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
     HttpResponsehttpResponse = httpClient.execute(get);

    //httpResponse的getEntity方法获取的对象中,包装了服务器的响应内容
     HttpEntityentity = httpResponse.getEntity();
     if(entity!= null)
     {
      //读取服务器响应
      BufferedReaderbr = new BufferedReader(newInputStreamReader(entity.getContent()));
      Stringline = 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);
    newAlertDialog.Builder(httpclient.this)
    .setTitle("登陆系统")
    .setView(loginDialog)
    .setPositiveButton("登陆",new DialogInterface.OnClickListener() {
     //嵌套着登陆按钮的监听函数
     publicvoid onClick(DialogInterface arg0, int arg1) {
      Stringname =((EditText)loginDialog.findViewById(R.id.name)).getText().toString();
      Stringpass =((EditText)loginDialog.findViewById(R.id.pass)).getText().toString();
      HttpPostpost = new HttpPost("http://222.18.174.132:8080/foo/login.jsp");
      //如果传递参数的个数比较多可以对传递的参数进行封装
      List<NameValuePair>params = newArrayList<NameValuePair>();
      params.add(newBasicNameValuePair("name", name));
      params.add(newBasicNameValuePair("pass", pass));
      try
      {
       //设置请求参数
       post.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));
       //发送post请求
       HttpResponseresponse = httpClient.execute(post);
       //如果服务器成功的返回响应
       if(response.getStatusLine().getStatusCode()== 200)
       {
        Stringmsg = EntityUtils.toString(response.getEntity());
        //提示登陆成功
        Toast.makeText(httpclient.this,msg, 5000).show();
       }
      }
      catch(Exceptione)
      {
       e.printStackTrace();
      }
     }
    }).setNegativeButton("取消",null).show();

 

用户名是crazyit.org  密码是leegang

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

使用Apache <wbr>httpclient

使用Apache <wbr>httpclient

代码

0 0
原创粉丝点击