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