1. 程式人生 > >Basic Auth請求的java和python實現方案

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()