下面的Android应用需要向指定页面发送请求,但该页面并不是一个简单的页面,只有当用户已经登录,而且登录用户的用户名是crazyit.org时才可访问该页面。如果使用HTTPURLConnection来访问该页面,那么需要处理的细节就太复杂了。

访问Web应用中被保护的页面,如果使用浏览器则十分简单,用户通过系统提供的登录页面登录系统,浏览器会负责维护与服务器之间的Session,如果用户登录的用户名、密码符合要求,就可以访问被保护资源了。

为了通过HttpClient来访问被保护页面,程序同样需要使用HttpClient来登录系统,只要应用程序使用同一个HttpClient发送请求,HttpClient会自动维护与服务器之间的Session状态,也就是说程序第一次使用HttpClient登录系统后,接下来使用HttpClient即可访问被保护的页面了。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class HttpClientTest extends Activity {
  Button get;
  Button login;
  EditText response;
  HttpClient httpClient;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_http_client_test);
    //创建DefaultHttpClient对象
    httpClient = new DefaultHttpClient();
    get = (Button) findViewById(R.id.get);
    login = (Button) findViewById(R.id.login);
    response = (EditText) findViewById(R.id.response);
    get.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        // 创建一个HttpGet对象
        HttpGet get = new HttpGet("http://172.18.5.198:8080/foo/secret.jsp");
        try {
          //发送GET请求
          HttpResponse httpResponse = httpClient.execute(get);
          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");
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
    login.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        final View loginDialog = getLayoutInflater()
              .inflate(R.layout.login, null);
        new AlertDialog.Builder(HttpClientTest.this)
              .setTitle("登录系统")
              .setView(loginDialog)
              .setPositiveButton("登录", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                  String name = ((EditText)loginDialog.findViewById(
                          R.id.username)).getText().toString();
                  String pass = ((EditText)loginDialog.findViewById(
                          R.id.password)).getText().toString();
                  HttpPost post = new HttpPost("http://172.18.5.198: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(HttpClientTest.this, msg, 5000).show();
                    }
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              }).setNegativeButton("取消", null).show();
        }
     });
  }

}

登陆成功后,HttpClient将会自动维护与服务器之间的连接,并维护与服务器之间的Session状态。

使用HttpClient访问被保护资源的更多相关文章

  1. 零基础学习java------38---------spring中关于通知类型的补充,springmvc,springmvc入门程序,访问保护资源,参数的绑定(简单数据类型,POJO,包装类),返回数据类型,三大组件,注解

    一. 通知类型 spring aop通知(advice)分成五类: (1)前置通知[Before advice]:在连接点前面执行,前置通知不会影响连接点的执行,除非此处抛出异常. (2)正常返回通知 ...

  2. webpy 访问局域网共享资源

    遇到一个问题: 在python shell 中调用局域网远程共享文件时,没问题.但是在webpy中调用时,报错:没有权限.那一定是apache设置问题. 网上找不到类似的方法,于是换个思路搜了一下“p ...

  3. c# 中HttpClient访问Https网站

    c# 中HttpClient访问Https网站,加入如下代码: handler = new HttpClientHandler() ;handler.AllowAutoRedirect = true; ...

  4. java实现利用httpclient访问接口

    HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...

  5. 转: android之虚拟机访问tomcat服务器资源

    最近在研究Android虚拟机访问tomcat服务器资源,所以找了个时间写下这篇博客和大家分享一下心得. 其实Android虚拟机访问tomcat服务器非常的简单,只要不要弄错IP地址就可以访问tom ...

  6. 使用Postman访问OAuth2保护的WebAPI

    Instantnoodle现时的WebAPI已经受Azure AD保护,平时直接输入URL的方式已经不能够正常访问到WebAPI 所有API都可以Swagger页面找到 http://getazdev ...

  7. cxf整合spring发布rest服务 httpclient访问服务

    1.创建maven web项目并添加依赖 pom.xml <properties> <webVersion>3.0</webVersion> <cxf.ver ...

  8. 使用HttpClient访问接口(Rest接口和普通接口)

    这里总结一下使用HttpClient访问外部接口的用法.后期如果发现有什么缺陷会更改.欢迎读者指出此方法的不足之处. 首先,创建一个返回实体: public class HttpResult { // ...

  9. Service系统服务(六):rsync基本用法、rsync+SSH同步、配置rsync服务端、访问rsync共享资源、使用inotifywait工具、配置Web镜像同步、配置并验证Split分离解析

    一.rsync基本用法 目标: 本例要求掌握远程同步的基本操作,使用rsync命令完成下列任务: 1> 将目录 /boot 同步到目录 /todir 下   2> 将目录 /boot 下的 ...

随机推荐

  1. 差之毫厘谬之千里!带你认识CPU后缀含义

    intel的几代CPU中,后缀字母主要有以下几种: M:笔记本专用CPU,一般为双核,M前面一位数字是0,意味着是标准电压处理器,如果是7,则是低电压处理器. U:笔记本专用低电压CPU,一般为双核, ...

  2. ElasticSearch(ES)和solr的关系和区别

    可以参考这篇文章:http://www.cnblogs.com/chowmin/articles/4629220.html Solr 2004年诞生(当时是Solar). ElasticSearch ...

  3. Oracle查看表结构的几种方法

    1,DESCRIBE 命令 使用方法如下: SQL> describe nchar_tst(nchar_tst为表名) 显示的结果如下:  名称                         ...

  4. Linux上安装Mysql后除了本机其他机器不能访问的问题(zhuan)

    http://blog.sina.com.cn/s/blog_a338027c0101esbs.html http://niutuku.com/tech/Mysql/237638.shtml http ...

  5. Struts2文件上传

    1  在Struts2中上传文件需要 commons-fileupload-1.2.1.jar.commons-io-1.3.2.jar 这两个包. 2  确认页面form表单上的提交方式为POST, ...

  6. listToString

    http://www.oschina.net/code/snippet_109648_2229

  7. karma+angular

    下面的介绍以karma能正常运行为前提,看karma系列文章:http://www.cnblogs.com/laixiangran/tag/Karma/ 目录结构 步骤 安装 npm install ...

  8. 工作常用的linux/mysql/php/工具命令

    工作常用的linux/mysql/php/工具命令: 1. tar备份目录 tar zcvf ****.tar.gz ****/ tar 备份跳过目录 tar --exclude=test1 3. s ...

  9. The Economist

      The turning point in the process of growing up is when you discover the core of strength within yo ...

  10. Form1和Form2的交互

    比如在第二个窗体中操作第一个窗体中的TreeView,动态添加节点和子节点. ------回答--------- ------其他回答(20分)--------- 尽量不要这样做.控件,窗体,你在.n ...