HTTP请求

Posted 否定之否定

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 + "\r\n");
            }
            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 + "\r\n");
            }
            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 + "\r\n");
            }
            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 + "\r\n");
//                }
//                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 ‘\t‘:
                outBuffer.append(‘\\‘);
                outBuffer.append(‘t‘);
                break;
            case ‘\n‘:
                outBuffer.append(‘\\‘);
                outBuffer.append(‘n‘);
                break;
            case ‘\r‘:
                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

 

以上是关于HTTP请求的主要内容,如果未能解决你的问题,请参考以下文章

postman 自动生成 curl 代码片段

如何对媒体片段的任何部分进行范围请求?

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

在哪里以及如何使用片段填充我的标签