package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import utils.FileSystem.JsonUtil;
import utils.FileSystem.WorkPath;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 接口工具类:如调用缓存刷新接口
*/
public class InterfaceUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceUtil.class);
public static void callInterface(String targetUrl, String data) {
HttpURLConnection conn = null;
BufferedReader br = null;
try {
URL url = new URL(targetUrl);
//获取HttpURLConnection实例
conn = (HttpURLConnection) url.openConnection();
PrintWriter out;
//请求方式
// conn.setRequestMethod("POST");
//设置连接超时
conn.setConnectTimeout(5000);
// //设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
//发送请求参数即数据
out.print(data);
//缓冲数据
out.flush();
//获取到服务器返回的输入流,字节输入流InputStream对象
InputStream in = conn.getInputStream();
//对获取到的输入流进行读取
br = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
LOGGER.info("调用接口结果==> {}", response);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
LOGGER.info("关闭流");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
LOGGER.info("关闭Http连接");
conn.disconnect();
}
}
}
/**
* 获取post请求参数
* @param StringName: json node
* @return
*/
public static String Request(String jsonFile, String StringName){
return String.valueOf(JsonUtil.getString(WorkPath.getDataPath(jsonFile), StringName));
}
public static void main(String[] args) {
callInterface("http://127.0.0.1/order/index/order?empId=110120&orderId=10000022211111", "");
callInterface(GlobalConfigHelper.getHttpHost(), Request("postRequest", "request1"));
}
}