HTTP Basic 认证(Authentication)

来源:互联网 发布:手机隐藏软件下载 编辑:程序博客网 时间:2024/04/26 23:41

什么是HTTP Basic Authentication?直接看http://en.wikipedia.org/wiki/Basic_authentication_scheme吧。

在你访问一个需要HTTP Basic Authentication的URL的时候,如果你没有提供用户名和密码,服务器就会返回401,如果你直接在浏览器中打开,浏览器会提示你输入用户名和密码(google浏览器不会,bug?)。你可以尝试点击这个url看看效果:http://api.minicloud.com.cn/statuses/friends_timeline.xml

要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:

一是在请求头中添加Authorization:
Authorization: “Basic 用户名和密码的base64加密字符串”
二是在url中添加用户名和密码:
http://userName:password@api.minicloud.com.cn/statuses/friends_timeline.xml
spring中的方式如下:

/** Add HTTP Authorization header, using Basic-Authentication to send user-credentials.*/private static HttpHeaders getHeaders(){        String plainCredentials="bill:abc123";        String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));        HttpHeaders headers = new HttpHeaders();        headers.add("Authorization", "Basic " + base64Credentials);        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));        return headers;    }

使用方法如下:

List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));        messageConverters.add(converter);        RestTemplate restTemplate = new RestTemplate();        restTemplate.setMessageConverters(messageConverters);        String plainCredentials="userName:password";        String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));        HttpHeaders headers = new HttpHeaders();        headers.add("Authorization", "Basic " + base64Credentials);        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));        HttpEntity<String> formEntity = new HttpEntity<String>("", headers);        String result = restTemplate.postForObject(url, formEntity, String.class);