PostMan添加Authorization验证
JAVA代码实现
String url ="URL路径";
Map<String, String> prarms = new HashMap<>();
prarms.put("userName","案例");
prarms.put("age", "18");
String jsonPrarms = JSON.toJSONString(prarms);
CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //获取浏览器信息
HttpPost httpPost = new HttpPost(url);
String encoding = DatatypeConverter.printBase64Binary("username:password".getBytes("UTF-8")); //username password 自行修改 中间":"不可少
httpPost.setHeader("Authorization", "Basic " + encoding);
HttpEntity entityParam = new StringEntity(jsonPrarms,ContentType.create("application/json", "UTF-8")); //这里的“application/json” 可以更换因为本人是传的json参数所以用的这个
httpPost.setEntity(entityParam); //把参数添加到post请求
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine(); //获取请求对象中的响应行对象
int responseCode = statusLine.getStatusCode();
if (responseCode == 200) {
//获取响应信息
HttpEntity entity = response.getEntity();
InputStream input = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(input,"utf-8"));
String str1 = br.readLine();
System.out.println("服务器的响应是:" + str1);
br.close();
input.close();
} else {
System.out.println("响应失败");
}
不足之处欢迎指出。