Phinehasz Zhi

超越你看到的

Basic Auth请求的java和python实现方案

java

使用apache的包,当时找了挺久轮子,最后在外网看到.

Basic Auth with Raw HTTP Headers
Preemptive Basic Authentication basically means pre-sending the Authorization header.

So – instead of going through the rather complex previous example to set it up, we can take control of this header and construct it by hand:

HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
byte[] encodedAuth = Base64.encodeBase64(
  auth.getBytes(StandardCharsets.ISO_8859_1));
String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
 
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
 
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

还是要回到basic auth的原理.原理是对username和password进行base64加密.
明文格式是:username:password
然后再作为请求头添加:
Authorization=Basic 密文
所以来看看python的实现方式

python

同样是python2.7, 3.6可以把urllib2换成urllib里的request

#!/usr/bin/env python
# coding=UTF-8
import urllib2
from base64 import encodestring

def get(url):
    username = 'admin'
    password = 'admin'
    req = urllib2.Request(url)
    basestr = encodestring('%s:%s' % (username, password))[:-1]
    req.add_header('Authorization', 'Basic %s' % basestr)
    return urllib2.urlopen(req).read()
posted @ 2018-12-22 13:21  phinehasz  阅读(847)  评论(0编辑  收藏  举报