BASIC HTTP AUTHENTICATION ON ANDROID
来源:互联网 发布:ios sql 编辑:程序博客网 时间:2024/05/21 23:33
This post belongs to the Day-saver snippets category, which is a series of simple code samples that will save you a day of research, which was exactly what they cost me.
You shouldn’t use HTTP basic authentication. It’s unsafe, since it sends the username and the password through the request headers. You should consider something like OAuth instead.
But, reasons aside, sometimes you’ll need to use it. And you’ll find that none of the documented methods work. You can try every single one of them without success. So you shouldn’t rely on the methods of the Apache library. You should do the authentication yourself.
HOW IT WORKS
Let’s cut to the chase: the client-side authentication consists on a HTTP header called Authorization. Its value is a Base64-encoded string, with the following format:
username:password
After encoded, the header will look like this:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Knowing that, we just need to create a header with that format and append to the request.
THE SNIPPET
Tho code below requires Android 2.2 to work (API level 8):
HttpUriRequest request = new HttpGet(YOUR_URL); // Or HttpPost(), depends on your needs
String credentials = YOUR_USERNAME + “:” + YOUR_PASSWORD;
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader(“Authorization”, “Basic ” + base64EncodedCredentials);
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(request);
// You’ll need to handle the exceptions thrown by execute()
Pay special attention to the Base64.NO_WRAP param. Without it, the snippet won’t work.
Hope it helps!
- BASIC HTTP AUTHENTICATION ON ANDROID
- BASIC HTTP AUTHENTICATION ON ANDROID
- Implement basic HTTP authentication
- HTTP: Basic Authentication
- HTTP Basic Authentication认证
- newlisp HTTP Basic Authentication
- HTTP: Basic Authentication
- HTTP Basic Authentication
- HTTP Basic Authentication认证
- HTTP Basic Authentication
- HTTP Basic Authentication认证
- HTTP Basic 认证(Authentication)
- HTTP Basic Authentication认证
- Basic HTTP authentication and Webdriver
- http 基础认证(Basic Authentication)
- HTTP Basic Authentication in JMeter
- Http Basic Authentication 新手版
- HTTP基础认证Basic Authentication
- 【Javaweb】Eclipse for JavaEE新建的Web工程自动生成web.xml
- Android 开源框架Universal-Image-Loader完全解析(二)--- 图片缓存策略详解
- AQS简介
- KNN算法
- 外网访问OpenWrt
- BASIC HTTP AUTHENTICATION ON ANDROID
- 简单模拟spring装载注入bean原理
- 2015年十大热门Android开源新项目
- Leetcode ☞ 83. Remove Duplicates from Sorted List
- Android 开源框架Universal-Image-Loader完全解析(三)---源代码解读
- 输出最大数和第二大数
- 1010. Radix (25)
- 高效的使用okhttp
- 深入分析Java ClassLoader原理