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();
}
相關文章
相關標籤/搜索