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

java

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

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

python

一样是python2.7, 3.6能够把urllib2换成urllib里的requestapache

#!/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()
相关文章
相关标签/搜索