android http协议添加Authorization认证方式
今天,简单讲讲android里如何使用http请求时在头部添加Authorization认证方式。
其实也很简单,之前需要做一个功能,在android去使用http访问设备,但是每次的访问需要用户名和密码作为Authorization请求。自己不知道怎么做,于是在网上搜素资料,最近是解决了问题。
如果通过抓包工具(Charles)可对比观察Authentication请求效果
其中Authorization就是验证的用户名和密码进行base64的字符串。下面分别介绍如何添加Authorization:
一.在OkHttp中使用Authorization认证是很简单的,如下:
//第一个参数为用户名,第二个参数为密码final String basic = Credentials.basic("zhangsan", "123456");OkHttpClient client = new OkHttpClient.Builder() .authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { return response.request().newBuilder().header("Authorization", basic).build(); } }) .build();Request request = new Request.Builder().url("http://192.168.45.2:8080/ha").build();client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d("--------", "onFailure: "+e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Log.d("---------", "onResponse: "+response.body().string()); } }});
二.HttpClient添加Authorization认证方式
1.Http put形式的
public static void invoke() { try { String url = "http://xxxxxx"; HttpGet httpReq = new HttpGet(url); httpReq.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials("Hello", "123456"), "UTF-8", false)); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpReq); StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( httpResponse.getEntity().getContent())); for (String s = reader.readLine(); s != null; s = reader.readLine()) { builder.append(s); } String result = builder.toString(); } catch (Exception e) { e.printStackTrace(); } }
HttpGet 在安卓API中已经过时,可以使用HttpUrlConnection httpGet还可以这样添加Authorization
public void HttpGetData() {try {HttpClient httpclient = new DefaultHttpClient();String uri = "http://www.yourweb.com"; HttpGet get = new HttpGet(uri);//添加http头信息 get.addHeader("Authorization", "your token ");get.addHeader("Content-Type", "application/json");get.addHeader("User-Agent","your agent");HttpResponse response;response = httpclient.execute(get);int code = response.getStatusLine().getStatusCode();//检验状态码,如果成功接收数据 if (code == 200) {//返回json格式: {"id": "27JpL~j4vsL0LX00E00005","version": "abc"} String rev = EntityUtils.toString(response.getEntity());obj = new JSONObject(rev); String id = obj.getString("id"); String version = obj.getString("version"); }} catch (Exception e) {}}
2.HttpPost添加Authorization
public static void getUserData() { //1.创建 HttpClient 的实例 try { //使用base64进行加密 //把认证信息发到header中 final String tokenStr = Base64.encode(("testclient" + ":testpass").getBytes()); HashMap hashMap = new HashMap(); String paramsStr = Utility.getHttpParamsStr(hashMap); StringEntity stringEntity = new StringEntity(paramsStr); stringEntity.setContentType("application/x-www-form-urlencoded"); HttpPost post = new HttpPost(API.loginCode); post.setHeader("Content-Type", "application/json"); post.setHeader("Authorization", tokenStr); HttpClient client = new DefaultHttpClient(); HttpResponse httpResponse = client.execute(post); String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block Logger.i("--------invoke--", "ClientProtocolException " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block Logger.i("--------invoke--", "IOException " + e.getMessage()); e.printStackTrace(); } }
HttpPost也属于已过时API 三.httpURLConnection添加Authorization认证方式
public class HttpUtils { /* * Function : 发送Post请求到服务器 * Param : params请求体内容,encode编码格式 */ public static String submitPostData(String strUrlPath, Map params, String encode) { byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体 try { URL url = new URL(strUrlPath); Logger.i("-------getUserId---", "url " + url); HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); httpURLConnection.setConnectTimeout(3000); //设置连接超时时间 httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据 httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据 httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据 httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存 //设置请求体的类型是文本类型 httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); //设置请求体的长度 httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length)); //获得输出流,向服务器写入数据 OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(data); // data 实际就是 map中的key=value 拼接的字符串 final String tokenStr = "Basic " + Base64.encode(("Hello" + ":123456").getBytes()); httpURLConnection.addRequestProperty("Authorization", tokenStr); int response = httpURLConnection.getResponseCode(); //获得服务器的响应码 if(response == HttpURLConnection.HTTP_OK) { InputStream inptStream = httpURLConnection.getInputStream(); return dealResponseResult(inptStream); //处理服务器的响应结果 } } catch (IOException e) { //e.printStackTrace(); return "err: " + e.getMessage().toString(); } return "-1"; } public static StringBuffer getRequestData(Map params, String encode) { StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息 try { for(Map.Entry entry : params.entrySet()) { stringBuffer.append(entry.getKey()) .append("=") .append(URLEncoder.encode(entry.getValue(), encode)) .append("&"); } stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&" } catch (Exception e) { e.printStackTrace(); } return stringBuffer; } /* * Function : 处理服务器的响应结果(将输入流转化成字符串) * Param : inputStream服务器的响应输入流 */ public static String dealResponseResult(InputStream inputStream) { String resultData = null; //存储处理结果 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; try { while((len = inputStream.read(data)) != -1) { byteArrayOutputStream.write(data, 0, len); } } catch (IOException e) { e.printStackTrace(); } resultData = new String(byteArrayOutputStream.toByteArray()); Logger.i("-------getUserId---", "dealResponseResult " + resultData); return resultData; }}
final String tokenStr = "Basic " + Base64.encode(("Hello" + ":123456").getBytes());
httpURLConnection.addRequestProperty("Authorization", tokenStr);
就是设置 Authentication 的关键,是Base64把用户名,密码以 name:key 方式加密,然后再加到
"Basic " 后面 ,二服务端会根据 Oauth框架进行解析,
简单讲讲,http请求添加Authorization认证方式 其实就是在http头部添加一个字段Authorization(HTTP授权的授权证书),它的值为Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==(用户名:密码的base64编码)。具体怎么添加,例子里写的很清楚。下面聚一下HTTP Request Header请求头信息对照表和HTTP Responses Header 响应头信息对照表。
HTTP Request Header请求头信息对照表:
Header | 解释 | 示例 |
---|---|---|
Accept | 指定客户端能够接收的内容类型 | Accept: text/plain, text/html |
Accept-Charset | 浏览器可以接受的字符编码集。 | Accept-Charset: iso-8859-5 |
Accept-Encoding | 指定浏览器可以支持的web服务器返回内容压缩编码类型。 | Accept-Encoding: compress, gzip |
Accept-Language | 浏览器可接受的语言 | Accept-Language: en,zh |
Accept-Ranges | 可以请求网页实体的一个或者多个子范围字段 | Accept-Ranges: bytes |
Authorization | HTTP授权的授权证书 | Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Cache-Control | 指定请求和响应遵循的缓存机制 | Cache-Control: no-cache |
Connection | 表示是否需要持久连接。(HTTP 1.1默认进行持久连接) | Connection: close |
Cookie | HTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器。 | Cookie: $Version=1; Skin=new; |
Content-Length | 请求的内容长度 | Content-Length: 348 |
Content-Type | 请求的与实体对应的MIME信息 | Content-Type: application/x-www-form-urlencoded |
Date | 请求发送的日期和时间 | Date: Tue, 15 Nov 2010 08:12:31 GMT |
Expect | 请求的特定的服务器行为 | Expect: 100-continue |
From | 发出请求的用户的Email | From: user@email.com |
Host | 指定请求的服务器的域名和端口号 | Host: www.zcmhi.com |
If-Match | 只有请求内容与实体相匹配才有效 | If-Match: "737060cd8c284d8af7ad3082f209582d" |
If-Modified-Since | 如果请求的部分在指定时间之后被修改则请求成功,未被修改则返回304代码 | If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
If-None-Match | 如果内容未改变返回304代码,参数为服务器先前发送的Etag,与服务器回应的Etag比较判断是否改变 | If-None-Match: "737060cd8c284d8af7ad3082f209582d" |
If-Range | 如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为Etag | If-Range: "737060cd8c284d8af7ad3082f209582d" |
If-Unmodified-Since | 只在实体在指定时间之后未被修改才请求成功 | If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
Max-Forwards | 限制信息通过代理和网关传送的时间 | Max-Forwards: 10 |
Pragma | 用来包含实现特定的指令 | Pragma: no-cache |
Proxy-Authorization | 连接到代理的授权证书 | Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Range | 只请求实体的一部分,指定范围 | Range: bytes=500-999 |
Referer | 先前网页的地址,当前请求网页紧随其后,即来路 | Referer: http://blog.csdn.net/coder_pig |
TE | 客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息 | TE: trailers,deflate;q=0.5 |
Upgrade | 向服务器指定某种传输协议以便服务器进行转换(如果支持) | Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 |
User-Agent | User-Agent的内容包含发出请求的用户信息 | User-Agent: Mozilla/5.0 (Linux; X11) |
Via | 通知中间网关或代理服务器地址,通信协议 | Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) |
Warning | 关于消息实体的警告信息 | Warn: 199 Miscellaneous warning |
HTTP Responses Header 响应头信息对照表:
Header | 解释 | 示例 |
---|---|---|
Accept-Ranges | 表明服务器是否支持指定范围请求及哪种类型的分段请求 | Accept-Ranges: bytes |
Age | 从原始服务器到代理缓存形成的估算时间(以秒计,非负) | Age: 12 |
Allow | 对某网络资源的有效的请求行为,不允许则返回405 | Allow: GET, HEAD |
Cache-Control | 告诉所有的缓存机制是否可以缓存及哪种类型 | Cache-Control: no-cache |
Content-Encoding | web服务器支持的返回内容压缩编码类型 | Content-Encoding: gzip |
Content-Language | 响应体的语言 | Content-Language: en,zh |
Content-Length | 响应体的长度 | Content-Length: 348 |
Content-Location | 请求资源可替代的备用的另一地址 | Content-Location: /index.htm |
Content-MD5 | 返回资源的MD5校验值 | Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ== |
Content-Range | 在整个返回体中本部分的字节位置 | Content-Range: bytes 21010-47021/47022 |
Content-Type | 返回内容的MIME类型 | Content-Type: text/html; charset=utf-8 |
Date | 原始服务器消息发出的时间 | Date: Tue, 15 Nov 2010 08:12:31 GMT |
ETag | 请求变量的实体标签的当前值 | ETag: "737060cd8c284d8af7ad3082f209582d" |
Expires | 响应过期的日期和时间 | Expires: Thu, 01 Dec 2010 16:00:00 GMT |
Last-Modified | 请求资源的最后修改时间 | Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT |
Location | 用来重定向接收方到非请求URL的位置来完成请求或标识新的资源 | Location: http://blog.csdn.net/coder_pig |
Pragma | 包括实现特定的指令,它可应用到响应链上的任何接收方 | Pragma: no-cache |
Proxy-Authenticate | 它指出认证方案和可应用到代理的该URL上的参数 | Proxy-Authenticate: Basic |
android http协议添加Authorization认证方式 就讲完了
就这么简单。
更多相关文章
- Android控件TextView中ellipsize属性(设置当文字长度超过textview
- Android之Broadcast Receiver的两种注册方式
- Android 网络请求简单使用方式
- android 截取验证码的两种实现方式
- Android中程序与Service交互的方式
- Android入门(4) 布局、JUnit、日志与数据存储访问方式