Java使用原生的HttpURLConnection发送http请求

/**
 * 发送http请求
 * @param message 发送的内容
 * @param snedUrl 请求的url
 * @return
 */
public static String sendRequest(String message, String snedUrl) {

    log.error("发送http请求 url:" + snedUrl + ",message:" + message);

    StringBuffer str = new StringBuffer();

    HttpURLConnection conn = null;

    try {

        URL url = new URL(snedUrl);
        conn = (HttpURLConnection) url.openConnection();
        //是否打开输入流 , 此方法默认为true
        conn.setDoInput(true);
        //是否打开输出流, 此方法默认为false
        conn.setDoOutput(true);
        //POST或者GET
        conn.setRequestMethod("POST");
        //GET支持缓存,POST不支持
        conn.setUseCaches(false);
        //链接超时时间 10s
        conn.setConnectTimeout(10000);
        //read超时时间 120s
        conn.setReadTimeout(120000);
        //表示链接
        conn.connect();

        //写入发送的数据(POST请求的时候才须要)
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
        out.write(message);
        out.flush();
        out.close();

        //判断请求返回的状态
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

            //读取返回的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

            String temp = null;

            while ((temp = in.readLine()) != null) {
                str.append(temp);
            }

            in.close();
        }

    } catch (Exception e) {
        log.error("发送http请求失败:" + e);
    } finally {
        if (null != conn) {
            conn.disconnect();
        }
    }

    log.info("http请求返回的数据:" + str.toString());

    return str.toString();
}
相关文章
相关标签/搜索