Http請求 post get

package com.sprucetec.tms.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * HttpInvoker.
 *
 * @author Yinqiang Du
 * @date 2016/8/11
 */
public class HttpInvokerUtils {
    /**
     * 日誌.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpInvokerUtils.class);

    /**
     * 發起http get 請求獲取返回結果.
     *
     * @param getURL 請求路徑 .
     * @return
     * @throws Exception
     */
    public static void readContentFromGet(String getURL) throws IOException {
        // 拼湊get請求的URL字串,使用URLEncoder.encode對特殊和不可見字符進行編碼
        URL getUrl = new URL(getURL);
        // 根據拼湊的URL,打開連接,URL.openConnection函數會根據 URL的類型,
        // 返回不同的URLConnection子類的對象,這裏URL是一個http,因此實際返回的是HttpURLConnection
        HttpURLConnection connection = (HttpURLConnection) getUrl
                .openConnection();
        // 進行連接,但是實際上get request要在下一句的 connection.getInputStream()函數中才會真正發到
        // 服務器
        connection.connect();
        // 取得輸入流,並使用Reader讀取
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        System.out.println(" ============================= ");
        System.out.println(" Contents of get request ");
        System.out.println(" ============================= ");
        String lines;
        while ((lines = reader.readLine()) != null) {
            System.out.println(lines);
        }
        reader.close();
        // 斷開連接
        connection.disconnect();
        System.out.println(" ============================= ");
        System.out.println(" Contents of get request ends ");
        System.out.println(" ============================= ");
    }

    /**
     * 發起http post 請求獲取返回結果.
     *
     * @param urlStr            請求路徑 .
     * @param requestParamsJson json字符串.
     * @return
     * @throws Exception
     */
    public static void sendRequest(String urlStr, String requestParamsJson) throws Exception {
        BufferedOutputStream bufOutPut = null;
        BufferedReader bufferedReader = null;
        HttpURLConnection httpConn = null;
        try {
            URL url = new URL(urlStr);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setDoInput(true); // 設置是否從httpUrlConnection讀入,默認情況下是true;
            httpConn.setDoOutput(true);  // 設置是否向httpUrlConnection輸出,因爲這個是post請求,參數要放在http正文內,因此需要設爲true, 默認情況下是false;
            httpConn.setRequestMethod("POST");// 設定請求的方法爲"POST",默認是GET
            httpConn.setAllowUserInteraction(false); //是否允許用戶交互
            httpConn.setUseCaches(false);  // Post 請求不能使用緩存
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestProperty("Accept-Charset", "UTF-8");
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長連接
            httpConn.setRequestProperty("Content-Type", "application/json");   // 設定傳送的內容類型是可序列化的java對象
            // 此處getOutputStream會隱含的進行connect(即:如同調用上面的connect()方法,
            bufOutPut = new BufferedOutputStream(httpConn.getOutputStream());
            httpConn.connect();
            byte[] bdat = requestParamsJson.getBytes("UTF-8");// 解決中文亂碼問題
            bufOutPut.write(bdat, 0, bdat.length);
            bufOutPut.flush();

            // 根據ResponseCode判斷連接是否成功
            int responseCode = httpConn.getResponseCode();
            if (responseCode != 200) {
                LOGGER.error(" Error===" + responseCode);
            } else {
                LOGGER.info("Post Success!");
            }
            // 定義BufferedReader輸入流來讀取URL的ResponseData
            bufferedReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            LOGGER.error("send post request error!" + e);
        } finally {
            httpConn.disconnect(); // 斷開連接
            try {
                if (bufOutPut != null) {
                    bufOutPut.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
發佈了29 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章