发送POST请求函数样例:
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;
public String sendPost(String requestUrl, String param) {
InputStream inputStream = null;
try {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(requestUrl);
// 设置请求头 Content-Type
postMethod.setRequestHeader("Content-Type", "application/json");
//Base64加密方式认证方式下的basic auth
postMethod.setRequestHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString(("username:password").getBytes()));
RequestEntity requestEntity = new StringRequestEntity(param,"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);
}
System.out.print("接口返回内容为:" + buffer);
return buffer.toString();
} catch (Exception e){
System.out.print("请求异常" +e.getMessage());
throw new RuntimeException(e.getMessage());
} finally {
if(inputStream != null) {
try{
inputStream.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
测试调用
import com.alibaba.fastjson.JSON;
Map<String, Object> prarms = new HashMap<>();
prarms.put("key", value);
String jsonPrarms = JSON.toJSONString(prarms);
mailEntity.sendPost("http://10.10.10.10:8000/mail", jsonPrarms);
|