使用HttpClient访问被保护资源
下面的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访问被保护资源的更多相关文章
- 零基础学习java------38---------spring中关于通知类型的补充,springmvc,springmvc入门程序,访问保护资源,参数的绑定(简单数据类型,POJO,包装类),返回数据类型,三大组件,注解
一. 通知类型 spring aop通知(advice)分成五类: (1)前置通知[Before advice]:在连接点前面执行,前置通知不会影响连接点的执行,除非此处抛出异常. (2)正常返回通知 ...
- webpy 访问局域网共享资源
遇到一个问题: 在python shell 中调用局域网远程共享文件时,没问题.但是在webpy中调用时,报错:没有权限.那一定是apache设置问题. 网上找不到类似的方法,于是换个思路搜了一下“p ...
- c# 中HttpClient访问Https网站
c# 中HttpClient访问Https网站,加入如下代码: handler = new HttpClientHandler() ;handler.AllowAutoRedirect = true; ...
- java实现利用httpclient访问接口
HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...
- 转: android之虚拟机访问tomcat服务器资源
最近在研究Android虚拟机访问tomcat服务器资源,所以找了个时间写下这篇博客和大家分享一下心得. 其实Android虚拟机访问tomcat服务器非常的简单,只要不要弄错IP地址就可以访问tom ...
- 使用Postman访问OAuth2保护的WebAPI
Instantnoodle现时的WebAPI已经受Azure AD保护,平时直接输入URL的方式已经不能够正常访问到WebAPI 所有API都可以Swagger页面找到 http://getazdev ...
- cxf整合spring发布rest服务 httpclient访问服务
1.创建maven web项目并添加依赖 pom.xml <properties> <webVersion>3.0</webVersion> <cxf.ver ...
- 使用HttpClient访问接口(Rest接口和普通接口)
这里总结一下使用HttpClient访问外部接口的用法.后期如果发现有什么缺陷会更改.欢迎读者指出此方法的不足之处. 首先,创建一个返回实体: public class HttpResult { // ...
- Service系统服务(六):rsync基本用法、rsync+SSH同步、配置rsync服务端、访问rsync共享资源、使用inotifywait工具、配置Web镜像同步、配置并验证Split分离解析
一.rsync基本用法 目标: 本例要求掌握远程同步的基本操作,使用rsync命令完成下列任务: 1> 将目录 /boot 同步到目录 /todir 下 2> 将目录 /boot 下的 ...
随机推荐
- iOS - UIImagePickerController
前言 NS_CLASS_AVAILABLE_IOS(2_0) @interface UIImagePickerController : UINavigationController <NSCod ...
- Web App时代的缓存机制新思路
Web App常见架构 以WebQQ例,WebQQ这个站点的所有内容都是一个页面里面呈现的,我们看到的类似windows操作系统的框架,是它的顶级容器和框架,由AlloyOS的内核负责统筹和管理,然后 ...
- elastic
学习链接 http://rfyiamcool.blog.51cto.com/1030776/1420811?utm_source=tuicool&utm_medium=referral
- 2014 Multi-University Training Contest 4
1006 hdu4902 #include <iostream> #include<stdio.h> #include<vector> #include<qu ...
- python的最最最最最基本语法(2)
函数的定义: 使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 当用return 返回多个值时,返回的其实是一个tuple, ...
- [css] 浏览器字体和css设置字体之间的关系
原文链接:http://www.zhangxinxu.com/wordpress/2010/06/%E5%8F%AF%E7%94%A8%E6%80%A7%E4%B9%8B%E6%B5%8F%E8%A7 ...
- openfire过滤脏话插件,控制消息是否发送
参考:http://myopenfire.com/article/getarticle/9 package com.myopenfire.plugin; import java.io.File; im ...
- Web服务器异常问题记录
1.使用命令,出现"-bash: 命令: Input/output error" 重启服务器后正常,网上查了下是说硬盘写入读取异常,经过和服务器厂商沟通后,确认是硬件问题导致(硬盘 ...
- PHP 实现多服务器共享 SESSION 数据
PHP 实现多服务器共享 SESSION 数据 2011 年 12 月 05 日评论暂缺 一.问题起源 稍大一些的网站,通常都会有好几个服务器,每个服务器运行着不同功能的模块,使用不同的二级域名,而一 ...
- R语言实战
教材目录 第一部分 入门 第一章 R语言介绍 第二章 创建数据集 第三章 图形初阶 第四章 基本数据管理 第五章 高级数据管理 第二部分 基本方法 第六章 基本图形 第七章 基本统计方法 第三部分 中 ...