java.net.HttpURLConnection;

  • Post author:
  • Post category:java


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;

import com.huawei.bme.commons.om.log.DebugLog;
import com.huawei.bme.commons.om.log.LogFactory;
import com.huawei.iread.util.DateUtil;
{
        // 响应码
        int sc = HttpURLConnection.HTTP_OK;
        
        // 记录入口日志,并加上时戳,以方便定位出其它系统无响应或响应慢方面的问题
        if (log.isInfoEnable())
        {
            log.info("begin sendHttp()..., request=" + request.toString() + ",requesurl =" + request.getUrl() + " ,to="
                + request.getTo() + ", response=" + response.toString() + ", timestamp=" + DateUtil.getCurrentTime());
        }
        
        final long start = System.currentTimeMillis();
        long delay = 0;
        
        InputStream in = null;
        OutputStream out = null;
        HttpURLConnection connect = null;
        ByteArrayOutputStream rspBuf = null;
        try
        {
            // 打开连接
            connect = (HttpURLConnection)request.getUrl().openConnection();
            
            // 设置超时时间
            int timeout = request.getConnectTimeout();
            if (0 <= timeout)
            {
                connect.setConnectTimeout(timeout);
            }
            
            connect.setDoInput(true); // 打开输入流(读取 服务器的输出)
            connect.setDoOutput(true); // 打开输出流(将请求 写到服务器)
            
            // 设置 method
            if (null != request.getRequestMethod())
            {
                connect.setRequestMethod(request.getRequestMethod());
            }
            
            // 设置 header
            String[][] headers = request.getAllHeaders();
            for (int i = 0; i < headers.length; i++)
            {
                connect.setRequestProperty(headers[i][0], headers[i][1]);
            }
            
            // 把请求 输出到服务器
            out = connect.getOutputStream();
            out.write(request.getReqBody());
            out.flush();
            
            // 读取服务器的响应
            sc = connect.getResponseCode();
            response.setResponseCode(sc);
            if (HttpURLConnection.HTTP_OK == sc)
            {
                // 设置响应编码
                String enc = connect.getContentEncoding();
                if (null == enc)
                {
                    String cntType = connect.getContentType();
                    if (null != cntType)
                    {
                        cntType = cntType.toLowerCase();
                        int idx = cntType.lastIndexOf("charset=");
                        if (0 < idx && (idx + 8) < cntType.length())
                        {
                            enc = cntType.substring(idx + 8).trim();
                        }
                    }
                }
                response.setCharset(enc);
                
                // 读取响应
                in = connect.getInputStream();
                // rspBuf = new BufferedInputStream(in);
                rspBuf = new ByteArrayOutputStream(1024 * 8);
                byte[] byteBuf = new byte[1024];
                int len = 0;
                while (0 < (len = in.read(byteBuf)))
                {
                    rspBuf.write(byteBuf, 0, len);
                }
                delay = System.currentTimeMillis() - start;
                
                // 解析响应
                response.parseResBody(new java.io.ByteArrayInputStream(rspBuf.toByteArray()));
            }
        }
        catch (Exception e)
        {
            sc = HttpURLConnection.HTTP_NOT_FOUND;
            delay = System.currentTimeMillis() - start;
            log.error("send http request failed", e);
        }
        finally
        {
            if (null != in)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    log.error("close HTTP InputStream failed", e);
                }
            }
            if (null != out)
            {
                try
                {
                    out.close();
                }
                catch (IOException e)
                {
                    log.error("close HTTP OutStream failed", e);
                }
            }
        }
        
        // 记录出口日志,并加上时戳,以方便定位出其它系统无响应或响应慢方面的问题
        String rspBody = null;
        if (log.isDebugEnable())
        {
            // 详细响应信息(为了性能考虑,只有日志为debug级别时才打印)
            String charset = response.getCharset();
            charset = ((null == charset) ? HttpReq.CHARSET_UTF8 : charset);
            if (null != rspBuf)
            {
                rspBody = ", rspBody=";
                try
                {
                    rspBody += new String(rspBuf.toByteArray(), charset);
                }
                catch (UnsupportedEncodingException e)
                {
                    log.error("parse response body failed", e);
                }
            }
        }
        
        if (log.isInfoEnable())
        {
            log.info("end sendHttp(), request=" + request.toString() + ", response=" + response.toString() + ", sc="
                + sc + ", timestamp=" + DateUtil.getCurrentTime() + ", delay=" + delay + "(ms)"
                + (null != rspBody ? rspBody.toLowerCase() : ""));
        }
        
        return sc;
    }



版权声明:本文为wjw_77原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。