Java原生HTTP请求工具类


import org.jsoup.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;


public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * @param requestUrl 请求地址
     * @param param      参数
     * @return strings of response
     */
    public static String doPUT(String requestUrl, String param) {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        StringBuilder responseBuilder = new StringBuilder();
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(String.valueOf(Connection.Method.PUT));
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/json");
            out = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8"));
            out.write(param);
            out.flush();
            int code = conn.getResponseCode();
            if (code == 200) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    responseBuilder.append(line);
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
                logger.error("error in HttpUtil,the request url:{},the param:{}", requestUrl, param, ex);
                //ignore
            }
        }
        return responseBuilder.toString();
    }
}

POST等请自行实现,举一反三

也可以写成内部类:



import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class Main {

    public static void main(String[] args) {
        String s = HttpUtil.doGet("http://www.baidu.com");
        System.out.println(s);
    }


    static class HttpUtil {

        private static final int READ_TIME_OUT = 5 * 1000;
        private static final int CONNECT_TIME_OUT = 5 * 1000;

        static String doGet(String url) {
            FineLoggerFactory.getLogger().info("----do http get:" + url);
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            StringBuilder response = new StringBuilder();
            try {
                URL reqUrl = new URL(url);
                connection = (HttpURLConnection) reqUrl.openConnection();
                connection.setReadTimeout(READ_TIME_OUT);
                connection.setConnectTimeout(CONNECT_TIME_OUT);
                connection.setDoInput(true);
                connection.setDoInput(true);
                connection.setRequestMethod(HttpMethod.GET.name());
                int code = connection.getResponseCode();
                if (code == HttpStatus.OK.value()) {
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                }
            } catch (Exception ex) {
                FineLoggerFactory.getLogger().error("error in HttpUtil");
                throw new RuntimeException(ex);
            } finally {
                close(reader, connection);
            }
            String result = response.toString();
            FineLoggerFactory.getLogger().info("----http get result:" + result);
            return result;
        }

        private static void close(BufferedReader reader, HttpURLConnection connection) {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (Exception ex) {
                FineLoggerFactory.getLogger().error("error in HttpUtil stream close", ex);
                //ignore
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值