使用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 下的 ...
随机推荐
- iOS8 获取通知设置状态
UIUserNotificationSettings *settings = [[UIApplication sharedApplication] currentUserNotificationSet ...
- 给input的按钮控件添加onserverclick事件
前台: <input type="button" value="登录" id="login" onclick="" ...
- thinkphp自动验证方法的使用
建一个表单: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...
- (六)C语言之typedef详解
1.typedef可以看作type define的缩写,顾名思义就是类型定义,也就是说它只是给已有的类型重新定义了一个方便使用的别名,并没有产生新的数据类型.typedef的使用与宏定义define有 ...
- iOS开发之APP推送设置WIFI
在iOS开发过程中,有时需要连接网络.当访问请求,检测到网络不可用时,需要提示用户手动进行设置网络并告知用户操作路径设置可用的网络. 只需一行代码即可实现: - (void)viewDidLoad { ...
- java 嵌套类 简记
嵌套类包括:1)静态嵌套类 (static 修饰符) 2)非静态嵌套类(又叫内部类) 其中内部类又可分为三种: 其一.在一个类(外部类)中直接定义的内部类: 其二.在一个方法(外部类的方法)中定义的 ...
- 获取iframe外边数据
http://biancheng.dnbcw.info/javascript/178184.html
- OpenCV C++ 计算文件夹中对象文件数目及批量处理后保存到txt文件
//采用windows控制台实现计算文件夹中对象总数以及批量读取对象 //#include <afx.h> //和windows.h是一样的作用 #include <opencv2/ ...
- mysql下sql语句 update 字段=字段+字符串
mysql下sql语句 update 字段=字段+字符串 mysql下sql语句令某字段值等于原值加上一个字符串 update 表明 SET 字段= 'feifei' || 字段; (postgr ...
- 自定义 密码是否可见 的EditView 右侧带个小眼睛
package com.qyk.douban.widget; import android.content.Context; import android.text.Editable; import ...