最近做的一个项目需要与其它系统对接接口,对方提供的是webservice的接口,并且需要Basic Authorization基本认证,一开始都是用postman请求,用户名和密码需要填在Basic Authorization中,类型是Basic Auth。但是在java的http请求中,不知道如何去实现Basic Authorization基本认证。
在请求的过程中,我发现Header中会包含Authorization为key的参数,值是Basic xxxxxxxxxxxxx形式。经过百度(参考:https://blog.csdn.net/a736889661/article/details/85328336)查询发现,这个值是 用户名:密码 经过base64加密后得到的值。
在java的http请求中可以按照下面的方式添加:
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
StringEntity entity;
StringBuilder s = null;
try {
httppost.setHeader("Content-Type", "application/json;charset=utf-8");
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Authorization", "Basic dXNlcjpwYXNzd29yZA==");
entity = new StringEntity(request.toString());
httppost.setEntity(entity);
HttpResponse response;
response = client.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
s = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
s.append(line).append('\n');
}
rd.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
关于http authorization讲的比较详细的微博,我参考了https://www.cnblogs.com/chenrong/articles/5818498.html。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)