• HTTP请求


    一:工具类HttpUtil

    package com.bw30.utils;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.ProtocolException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.log4j.Logger;
    
    public class HttpUtil {
    
        private static final int CONNECT_OUTTIME = 10000;
        private static final int READ_OUTTIME = 10000;
        private static final Logger logger = Logger.getLogger(HttpUtil.class);
    
        private static final String SERVLET_POST = "POST";
        private static final String SERVLET_GET = "GET";
        private static final String SERVLET_DELETE = "DELETE";
        private static final String SERVLET_PUT = "PUT";
    
        public static String getRequetString(HttpServletRequest req)
                throws IOException {
            String returnStr = "";
            BufferedInputStream bis = null;
            ByteArrayOutputStream bos = null;
            try {
                bis = new BufferedInputStream(req.getInputStream());
                bos = new ByteArrayOutputStream();
    
                int b = bis.read();
    
                while (b >= 0) {
                    bos.write(b);
                    b = bis.read();
                }
                returnStr = new String(bos.toByteArray(), "UTF-8");
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bis != null) {
                        bis.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return returnStr.trim();
        }
    
        /***
         * 发送get请求
         * @param url
         * @param enc
         * @return
         */
        public static String getUrl(String serverUrl, String enc) {
    
            HttpURLConnection conn = null;
            BufferedReader br = null;
            StringBuffer response = new StringBuffer();
            
            logger.info("Get请求:" + serverUrl);
            
            if (CommonTool.isStrEmpty(enc)) {
                enc = "UTF-8";
            }
            
            try {
                URL url = new URL(serverUrl);
                
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(CONNECT_OUTTIME);
                conn.setReadTimeout(READ_OUTTIME);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod(SERVLET_GET);
                conn.setRequestProperty("Content-Type", "text/html; charset=" + enc);
                
                conn.connect();
                
                logger.info("响应代码:" + conn.getResponseCode());
                br = new BufferedReader(new InputStreamReader(conn.getInputStream(), enc));
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line + "
    ");
                }
                if (response.length() > 1) {
                    response.delete(response.length() - 2, response.length());
                }
    
            } catch (MalformedURLException e1) {
                logger.error("执行HTTP Get请求" + serverUrl + "时,发生MalformedURLException异常!", e1);
            } catch (ProtocolException e1) {
                logger.error("执行HTTP Get请求" + serverUrl + "时,发生ProtocolException异常!", e1);
            } catch (IOException e1) {
                logger.error("执行HTTP Get请求" + serverUrl + "时,发生IOException异常!", e1);
            } finally {
                try {
                    if (br != null) {
                        br.close();
                        br = null;
                    }
                    if (conn != null) {
                        conn.disconnect();
                        conn = null;
                    }
                } catch (IOException e) {
                }
            }
            
            logger.info("响应内容:" + response.toString());
            
            return response.toString();
        }
    
        public static String postUrl(String serverUrl, String content, String enc) {
            HttpURLConnection conn = null;
            BufferedOutputStream out = null;
            BufferedReader in = null;
            StringBuffer response = new StringBuffer();
            
            if (content == null) {
                content = "";
            }
            
            logger.info("Post请求:" + serverUrl);
            if (!content.isEmpty()) {
                logger.info("请求参数: " + content);
            }
    
            if (CommonTool.isStrEmpty(enc)) {
                enc = "UTF-8";
            }
    
            try {
                URL url = new URL(serverUrl);
                
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("Content-Length", Integer
                        .toString(content.getBytes(enc).length));
    //            conn.setRequestProperty("Content-type",
    //                    "application/x-java-serialized-object");// application/x-www-form-urlencoded
                conn.setRequestProperty("Content-type",
                        "application/x-www-form-urlencoded");
                conn.setRequestMethod(SERVLET_POST);
                conn.setConnectTimeout(CONNECT_OUTTIME);
                conn.setReadTimeout(READ_OUTTIME);
                conn.setDoOutput(true);
                conn.setDoInput(true);
                
                // @post xml
                out = new BufferedOutputStream(conn.getOutputStream());
                StringBuffer buffer = new StringBuffer(content.length());
                buffer.append(content);
                out.write(buffer.toString().getBytes(enc));
                out.flush();
                
                // @make xml
                logger.info("响应代码:" + conn.getResponseCode());
                in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream(), enc));
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line + "
    ");
                }
                if (response.length() > 1) {
                    response.delete(response.length() - 2, response.length());
                }
                
            } catch (MalformedURLException e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生MalformedURLException异常!", e1);
            } catch (UnsupportedEncodingException e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生UnsupportedEncodingException异常!", e1);
            } catch (ProtocolException e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生ProtocolException异常!", e1);
            } catch (IOException e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生IOException异常!", e1);
            } catch (Exception e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生Exception异常!", e1);
            } finally {
                try {
                    if (out != null) {
                        out.close();
                        out = null;
                    }
                    if (in != null) {
                        in.close();
                        in = null;
                    }
                    if (conn != null) {
                        conn.disconnect();
                        conn = null;
                    }
                } catch (IOException e) {
                }
            }
            
            logger.info("响应内容:" + response.toString());
    
            return response.toString();
        }
        
        public static String postXml(String serverUrl, String content, String enc) {
            HttpURLConnection conn = null;
            BufferedOutputStream out = null;
            BufferedReader in = null;
            StringBuffer response = new StringBuffer();
            
            if (content == null) {
                content = "";
            }
            
            logger.info("Post请求:" + serverUrl);
            if (!content.isEmpty()) {
                logger.info("请求参数: " + content);
            }
            
            if (CommonTool.isStrEmpty(enc)) {
                enc = "UTF-8";
            }
            
            try {
                URL url = new URL(serverUrl);
                
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("Content-Length", Integer.toString(content.getBytes(enc).length));
                conn.setRequestProperty("Content-type", "text/html; charset=" + enc);
                conn.setRequestMethod(SERVLET_POST);
                conn.setConnectTimeout(CONNECT_OUTTIME);
                conn.setReadTimeout(READ_OUTTIME);
                conn.setDoOutput(true);
                conn.setDoInput(true);
                
                // @post xml
                out = new BufferedOutputStream(conn.getOutputStream());
                StringBuffer buffer = new StringBuffer(content.length());
                buffer.append(content);
                out.write(buffer.toString().getBytes(enc));
                out.flush();
                
                // @make xml
                logger.info("响应代码:" + conn.getResponseCode());
                in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream(), enc));
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line + "
    ");
                }
                if (response.length() > 1) {
                    response.delete(response.length() - 2, response.length());
                }
                
            } catch (MalformedURLException e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生MalformedURLException异常!", e1);
            } catch (UnsupportedEncodingException e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生UnsupportedEncodingException异常!", e1);
            } catch (ProtocolException e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生ProtocolException异常!", e1);
            } catch (IOException e1) {
                logger.error("执行HTTP Post请求" + serverUrl + "时,发生IOException异常!", e1);
            } finally {
                
                try {
                    if (out != null) {
                        out.close();
                        out = null;
                    }
                    if (in != null) {
                        in.close();
                        in = null;
                    }
                    if (conn != null) {
                        conn.disconnect();
                        conn = null;
                    }
                } catch (IOException e) {
                }
            }
            
            logger.info("响应内容:" + response.toString());
            
            return response.toString();
        }
    
        /**
         * 
         * 执行一个HTTP POST 请求,返回响应字符串
         * 
         * @param url
         *            请求的URL地址
         * @param params
         *            请求参数
         * @return 返回响应字符串
         * @throws UnsupportedEncodingException
         */
    //    public static String doPost(String url, Map<String, String> params)
    //            throws UnsupportedEncodingException {
    //        StringBuffer response = new StringBuffer();
    //        HttpClient client = new HttpClient();
    //        PostMethod method = new PostMethod(url);
    //
    //        // 设置Http Post数据
    //        if (params != null) {
    //            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
    //            int i = 0;
    //            for (Map.Entry<String, String> entry : params.entrySet()) {
    //                logger.info("post 请求参数名:" + entry.getKey() + " | 参数值:"
    //                        + entry.getValue());
    //                // (java.net.URLEncoder.encode(entry.getValue(),"UTF-8"))
    //                nameValuePairs[i] = new NameValuePair(entry.getKey(),
    //                        (java.net.URLEncoder.encode(entry.getValue(), "UTF-8")));
    //                i++;
    //            }
    //            method.setRequestBody(nameValuePairs);
    //        }
    //
    //        try {
    //            client.executeMethod(method);
    //            if (method.getStatusCode() == HttpStatus.SC_OK) {
    //                BufferedReader reader = new BufferedReader(
    //                        new InputStreamReader(method.getResponseBodyAsStream(),
    //                                "UTF-8"));
    //                String line;
    //                while ((line = reader.readLine()) != null) {
    //                    response.append(line);
    //                }
    //                reader.close();
    //            }
    //        } catch (IOException e) {
    //            logger.error("执行HTTP Post请求" + url + "时,发生异常!", e);
    //        } finally {
    //            method.releaseConnection();
    //        }
    //        return response.toString();
    //    }
    //
    //    public static String doGet(String url) {
    //        StringBuffer response = new StringBuffer();
    //        HttpClient client = new HttpClient();
    //        GetMethod method = new GetMethod(url);
    //
    //        try {
    //            client.executeMethod(method);
    //            if (method.getStatusCode() == HttpStatus.SC_OK) {
    //                BufferedReader reader = new BufferedReader(
    //                        new InputStreamReader(method.getResponseBodyAsStream(),
    //                                "UTF-8"));
    //                String line;
    //                while ((line = reader.readLine()) != null) {
    //                    response.append(line + "
    ");
    //                }
    //                reader.close();
    //            }
    //        } catch (HttpException e) {
    //            logger.error("执行HTTP Get请求" + url + "时,发生HttpException异常!", e);
    //        } catch (UnsupportedEncodingException e) {
    //            logger.error("执行HTTP Get请求" + url
    //                    + "时,发生UnsupportedEncodingException异常!", e);
    //        } catch (IOException e) {
    //            logger.error("执行HTTP Get请求" + url + "时,发生IOException异常!", e);
    //        } finally {
    //            method.releaseConnection();
    //        }
    //
    //        return response.toString();
    //    }
    
        /**
         * 生成请求内容字符串
         * 
         * @param datamap
         * @param params
         * @return
         * @throws UnsupportedEncodingException
         */
        public static String generteRequestContent(Map<String, String> datamap,
                String[] params) {
            StringBuffer stringBuffer = new StringBuffer();
            
            if (params == null) {
                return "";
            }
    
            for (int i = 0; i < params.length; i++) {
                String val = (datamap != null) ? datamap.get(params[i]) : "";
                if (val != null) {
                    stringBuffer.append(params[i]);
                    stringBuffer.append("=");
                    stringBuffer.append(val);
                    
                    if (i != params.length - 1) {
                        stringBuffer.append("&");
                    }
                }
            }
    //        logger.info("请求参数: " + stringBuffer.toString());
            return stringBuffer.toString();
        }
        
        /**
         * 生成请求内容字符串(对val进行url编码)
         * 
         * @param datamap
         * @param enc 默认utf-8
         * @return
         * @throws UnsupportedEncodingException
         */
        public static String generteRequestContent(Map<String, String> datamap, String enc) throws UnsupportedEncodingException {
            StringBuffer buffer = new StringBuffer();
            
            if (enc == null || enc.isEmpty()) {
                enc = "UTF-8";// 默认编码
            }
            
            Set<Entry<String, String>> entrySet = datamap.entrySet();
            for (Entry<String, String> entry : entrySet) {
                String key = entry.getKey();
                String val = entry.getValue();
                if (key != null && !key.isEmpty() && val != null) {
                    buffer.append("&");
                    buffer.append(key);
                    buffer.append("=");
                    buffer.append(URLEncoder.encode(val, enc));
                }
            }
            
            if (buffer.length() > 0) {
                return buffer.substring(1).toString();
            }
            return "";
            
    //        for (int i = 0; i < params.length; i++) {
    //            String val = (datamap != null) ? datamap.get(params[i]) : "";
    //            if (val != null) {
    //                buffer.append(params[i]);
    //                buffer.append("=");
    //                buffer.append(val);
    //                
    //                if (i != params.length - 1) {
    //                    buffer.append("&");
    //                }
    //            }
    //        }
    ////        logger.info("请求参数: " + stringBuffer.toString());
    //        return buffer.toString();
        }
    
        /**
         * 将字符串编码成 Unicode 。
         * 
         * @param theString
         *            待转换成Unicode编码的字符串。
         * @param escapeSpace
         *            是否忽略空格。
         * @return 返回转换后Unicode编码的字符串。
         */
        public static String toUnicode(String theString, boolean escapeSpace) {
            int len = theString.length();
            int bufLen = len * 2;
            if (bufLen < 0) {
                bufLen = Integer.MAX_VALUE;
            }
            StringBuffer outBuffer = new StringBuffer(bufLen);
    
            for (int x = 0; x < len; x++) {
                char aChar = theString.charAt(x);
                // Handle common case first, selecting largest block that
                // avoids the specials below
                if ((aChar > 61) && (aChar < 127)) {
                    if (aChar == '\') {
                        outBuffer.append('\');
                        outBuffer.append('\');
                        continue;
                    }
                    outBuffer.append(aChar);
                    continue;
                }
                switch (aChar) {
                case ' ':
                    if (x == 0 || escapeSpace)
                        outBuffer.append('\');
                    outBuffer.append(' ');
                    break;
                case '	':
                    outBuffer.append('\');
                    outBuffer.append('t');
                    break;
                case '
    ':
                    outBuffer.append('\');
                    outBuffer.append('n');
                    break;
                case '
    ':
                    outBuffer.append('\');
                    outBuffer.append('r');
                    break;
                case 'f':
                    outBuffer.append('\');
                    outBuffer.append('f');
                    break;
                case '=': // Fall through
                case ':': // Fall through
                case '#': // Fall through
                    break;
                case '!':
                    outBuffer.append('\');
                    outBuffer.append(aChar);
                    break;
                default:
                    if ((aChar < 0x0020) || (aChar > 0x007e)) {
                        outBuffer.append('\');
                        outBuffer.append('u');
                        outBuffer.append(toHex((aChar >> 12) & 0xF));
                        outBuffer.append(toHex((aChar >> 8) & 0xF));
                        outBuffer.append(toHex((aChar >> 4) & 0xF));
                        outBuffer.append(toHex(aChar & 0xF));
                    } else {
                        outBuffer.append(aChar);
                    }
                }
            }
            return outBuffer.toString();
        }
    
        private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6',
                '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    
        private static char toHex(int nibble) {
            return hexDigit[(nibble & 0xF)];
        }
    
    }
    View Code
  • 相关阅读:
    视频高清直播RTMP视频推流组件EasyRTMP-IOS版如何使用wchar_t*类型参数?
    设计模式
    算法学习【第10篇】:算法之动态规划问题
    算法学习【第9篇】:算法之斐波那契数列
    算法学习【第8篇】:贪心算法找零问题
    算法学习【第7篇】:算法之迷宫问题
    算法学习【第6篇】:算法之数据结构
    算法学习【第5篇】:常用排序算法(*******)
    算法学习【第4篇】:算法之---堆的简单介绍
    算法学习【第3篇】:树和二叉树简介
  • 原文地址:https://www.cnblogs.com/fdzfd/p/7149357.html
Copyright © 2020-2023  润新知