其实查了很多片文章,介绍怎么设置Authorization的办法,自我感觉讲的不太明晰。经过自己琢磨并且实地测试,最后感觉很easy!
1.先看看postman上怎么操作的,加Authorization无谓乎就是为了身份认证。所以,它后面所需值一般就是token
通过图片可得,用postman设置Authorization的时候,是把它放在头信息那个位置。所以,可想而知,这个东西要放在程序中,应该怎么处理?
①在设置Authorization这个之前,可以参考一下上面那个参数Content-Type,就可以得出,在java 中它应该设置在哪!
使用Header传递Authorization认证参数
上干货
代码部分:
/**
* Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
* 参数一:请求Url
* 参数二:请求的JSON
* 参数三:请求回调
*/
public static JSONObject postJsonParams(String url, String jsonParams) {
JSONObject responseBody = null;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder()
.url(url)
.header("Authorization", ""+ParseConfigFiles.getPropertValue("tokenInfo")+"")
.post(requestBody)
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return JSONObject.parseObject(response.body().string());
}
} catch (Exception e) {
logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
注:本章中
.header("Authorization", ""+ParseConfigFiles.getPropertValue("tokenInfo")+"")
的ParseConfigFiles.getPropertValue("tokenInfo")这个,是我的一个获取token值的表达式,此处按照自己实际情况处理,可以直接将token或者其它认证字符串放里面!