Java中http请求

/**
     * Http请求
     * 
     * @param url         请求地址
     * @param requestType 请求方式(GET,POST)
     * @return String
     */
    public static String sendRequest(String httpUrl, String requestType) {
        HttpURLConnection con = null;
        BufferedReader reader = null;
        StringBuilder result = null;
        InputStream stream = null;
        try {
            URL url = new URL(httpUrl);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod(requestType);
            con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            int respon = con.getResponseCode();
            if (respon == 200) {
                stream = con.getInputStream();
                result = new StringBuilder();
                String line;
                reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return result.toString();
            }
        } catch (Exception e) {
            log.error("请求异常:" + e.toString());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("关闭读取流失败:" + e.toString());
                }
            }
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("关闭流失败:" + e.toString());
                }
            }
            if (con != null) {
                con.disconnect();
            }
        }
        return "";
    }
View Code
原文地址:https://www.cnblogs.com/ZJ199012/p/15307400.html