CallaMOM.java 8.01 KB
package com.huaheng.api.mes.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.huaheng.api.mes.result.ReturnInfo;
import com.huaheng.common.utils.http.HttpUtils;
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.pc.monitor.apilog.domain.ApiLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.util.List;

public class CallaMOM {

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    public static ReturnInfo getMsg(String action, JSONObject JObject,String apiName,String url) {
        ReturnInfo info=null;
        String result = "";
        ApiLog apiLog = new ApiLog();
        HttpURLConnection urlConnection = null;
        OutputStreamWriter out = null;
        InputStream is = null;
        try {
            //URL url = new URL("http://192.168.100.127:31055//Handler/H_DJ2J_10.ashx");
            URL url1 = new URL(url);
            //通过调用url.openConnection()来获得一个新的URLConnection对象,并且将其结果强制转换为HttpURLConnection.
            urlConnection = (HttpURLConnection) url1.openConnection();
            urlConnection.setRequestMethod("POST");
            //设置连接的超时值为30000毫秒,超时将抛出SocketTimeoutException异常
            urlConnection.setConnectTimeout(40000);
            //设置读取的超时值为30000毫秒,超时将抛出SocketTimeoutException异常
            urlConnection.setReadTimeout(40000);
            //将url连接用于输出,这样才能使用getOutputStream()。getOutputStream()返回的输出流用于传输数据
            urlConnection.setDoOutput(true);
            //设置通用请求属性为默认浏览器编码类型
            urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            String content =""+JObject;
            String content2 = "sptype=JSP_W2M&action=" + action + "&onlydata=1&params=" + JObject;
            apiLog = ApiLogAspect.initApiLog(urlConnection, content, "CS0001",apiName);
            urlConnection.connect();
            out = new OutputStreamWriter( urlConnection.getOutputStream(),"UTF-8");// utf-8编码
            out.append(content2);
            out.flush();
            out.close(); // 读取响应
            int length = (int) urlConnection.getContentLength();// 获取长度
            is = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            length = 10000;
            if(length > 0) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                result = new String(data, "UTF-8");
                //System.out.println(result);

                JSONObject jsonResult = JSON.parseObject(result);
                //String status = jsonResult.getString("status");
                //String message = jsonResult.getString("message");
                JSONObject jsonData = jsonResult.getJSONObject("data");
                info = JSON.toJavaObject(jsonData, ReturnInfo.class);

                //String curd = info.getCurd();
                //String responder = info.getResponder();
                //Integer code = info.getCode();
                //String msg = info.getMsg();
            }
//            //getOutputStream()返回的输出流,用于写入参数数据。
//            OutputStream outputStream = urlConnection.getOutputStream();
//            apiLog = ApiLogAspect.initApiLog(urlConnection, JObject.toString(), "CS0001");
//            // String content = "grant_type=password&app_key="+APP_KEY+"&app_secret="+APP_SECRET;
//            String content = "sptype=JSP_W2M&action=" + action + "&onlydata=1&params=" + JObject;;
//            outputStream.write(content.getBytes());
//            outputStream.flush();
//            outputStream.close();
//            //此时将调用接口方法。getInputStream()返回的输入流可以读取返回的数据。
//            InputStream inputStream = urlConnection.getInputStream();
//            byte[] data = new byte[1024];
//            StringBuilder sb = new StringBuilder();
//            //inputStream每次就会将读取1024个byte到data中,当inputSteam中没有数据时,inputStream.read(data)值为-1
//            while (inputStream.read(data) != -1) {
//                String s = new String(data, "UTF-8");
//                sb.append(s);
//            }
//            // result = sb.toString();
//            inputStream.close();
        } catch (IOException e) {
            ApiLogAspect.setApiLogException(apiLog, e);
            log.error("调用HttpUtils.sendPost IOException, url=" + url+ action + ",param=" + JObject, e.getMessage());
        } finally {
            ApiLogAspect.finishApiLog(apiLog, urlConnection, result,apiName);
        }
        return info;
    }


    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            String urlNameString = url + "?" + param;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setRequestProperty("sptype", "JSP_W2M");
            conn.setRequestProperty("action", "E_Rd_In");
            conn.setRequestProperty("onlydata", "1");
            conn.setRequestProperty("params", "data:{}");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            if (((HttpURLConnection)conn).getResponseCode() >= 390) {
                in = new BufferedReader(new InputStreamReader(((HttpURLConnection) conn).getErrorStream()));
            } else {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
//            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e.getMessage());
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex.getMessage());
            }
        }
        return result.toString();
    }


}