package com.steerinfo.ems.Utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpRequestMes {
	
	private static final Logger logger = LoggerFactory.getLogger(HttpRequestMes.class);
	
    /**
	 * MES数据接口访问
	 * 
	 * @param requestUrl    接口地址
	 * @param requestMethod 请求方法
	 * @param outputStr     参数
	 * @return
	 */
	public static String httpRequestMes(String requestUrl, String requestMethod, String outputStr) {
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {
			// 建立连接
			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setRequestMethod(requestMethod.toUpperCase());
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

			String auth = "admin:interface2019";
			String res = new String(Base64.getEncoder().encode(auth.getBytes()));
			// 设置认证属性
			httpUrlConn.setRequestProperty("Authorization", "Basic " + res);
			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
			}
			// 当有数据需要提交时
			if (outputStr != null && !"GET".equalsIgnoreCase(requestMethod)) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.flush();
				outputStream.close();
			}
			// 获取输入流
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			// 读取返回结果
			buffer = new StringBuffer();
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
		} catch (Exception e) {
			// e.printStackTrace();
			logger.error("接口访问错误,url:" + requestUrl + ",requestMethod:" + requestMethod + ",outputStr:" + outputStr);
			logger.error(e.getMessage());
		} finally{
            if(httpUrlConn!=null){
            	httpUrlConn.disconnect();
            }
		}
		return buffer.toString();
	}
}