import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class JAVACallPORestDemo {
public String load(String url, String query) throws Exception {
String line, resultStr = "";
HttpURLConnection conn = null;
OutputStream out = null;
BufferedReader br = null;
try {
// 用户名
String username = "";
// 密码
String password = "";
// 认证参数
String author = "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
URL restURL = new URL(url);
conn = (HttpURLConnection) restURL.openConnection();
// 设置请求方式
conn.setRequestMethod("POST");
// 设置接收文件类型
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
// 权限认证
conn.setRequestProperty("Authorization", author);
// conn.setAllowUserInteraction(false);
// 开始连接
conn.connect();
// 传递参数 流的方式
out = conn.getOutputStream();
out.write(query.getBytes());
out.flush();
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
while (null != (line = br.readLine())) {
resultStr += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭所有通道
try {
if (br != null) {
br.close();
}
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return resultStr;
}
public static void main(String[] args) {
try {
RestDemo restUtil = new RestDemo();
String resultString = restUtil.load("http://IP:50100/RESTAdapter/PO/GetExchangeRates",
"{\"DT_GetExchangeRatesReq\":{\"Date\":\"2021-08-30\"}}");
// 接收的数据
System.out.println("result==" + resultString);
// 然后对数据进行JSON解析
} catch (Exception e) {
// TODO: handle exception
System.out.print(e.getMessage());
}
}
}