PostMan添加Authorization验证
pom.xml添加依赖包
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
通过PostMethod的方式(工具类)
package com.topnet.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Base64;
/**
* TODO
* 外部接口调用Post
* @author hejie
* @date 2021/7/29 17:13
*/
@Slf4j
public class PostMethodUtils {
/**
* 发送HttpClient请求
* @param requestUrl
* @param params
* @return
*/
public static String sendPost(String requestUrl, String params ) {
InputStream inputStream = null;
try {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(requestUrl);
// 设置请求头 Content-Type
postMethod.setRequestHeader("Content-Type", "application/json");
//Base64加密方式认证方式下的basic auth HAIN460000:用户名 topicis123:密码
postMethod.setRequestHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString(("HAIN460000" + ":" + "topicis123").getBytes()));
RequestEntity requestEntity = new StringRequestEntity(params,"application/json","UTF-8");
postMethod.setRequestEntity(requestEntity);
httpClient.executeMethod(postMethod);// 执行请求
inputStream = postMethod.getResponseBodyAsStream();// 获取返回的流
BufferedReader br = null;
StringBuffer buffer = new StringBuffer();
// 将返回的输入流转换成字符串
br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
}
log.info("接口返回内容为:" + buffer);
return buffer.toString();
} catch (Exception e){
log.info("请求异常" +e.getMessage());
throw new RuntimeException(e.getMessage());
} finally {
if(inputStream != null) {
try{
inputStream.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
}
测试
String parameter = "{ \"dto\":{\"purchaserPhone\":\"13798479813\" }}";
PostMethodUtils.sendPost(requestUrl,parameter);
结果
{
"status":200,
"data":[
{
"id":10612514,
"Name":"张三",
"Dept":520100,
"DeptCode":"fdrre",
"DeptName":"贵州",
"Date":"2020-12-05"
}
]
}