使用Java發送http請求,不使用第三方庫


HTTP協議是現在互聯網廣泛使用的數據傳輸協議,幾乎任何一種編程語言都實現了這個協議。Java語言是做web應用(服務器端應用)的強大語言。不過,現在我們使用Java語言來做客戶端,發送http請求到服務器,並獲取服務器的響應結果。

目前,絕大多數人都會使用第三方的框架,比如Apache的httpclient,在高版本的java中甚至內置了一個輕量級的http客戶端類,但我這次使用原生的方式去發送,不依賴任何第三方的東西,使用JavaSE就可以完成。

  • Java發送http請求需要使用一個叫URL的類,他的構造方法可以接受一個網址,就是我們想要發送請求的地址。
  • 然后,通過這個URL的實例,就可以打開一個連接。
  • 之后,通過這個連接可以讀寫數據。
  • 最后,關閉數據讀寫連接。

下面,展示代碼,並附上說明:

    public String httpRequest(String url) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        
        // 設置http請求頭,content-type為你發送請求參數的數據格式,目前來說application/json用的比較多,常用的三種
        // 1.application/json 2.application/x-www-form-urlencoded 3.multipart/form-data; boundary=xxxxxxx
        // 第一種,就是使用json的格式發送請求參數,類似{"name":"xxx","age":18},第二種使用urlencode的形式發送請求參數
        // 類似name=xxx&age=18,第三種就比較復雜點了,可以支持上傳文件,本次不做示例展示
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//        connection.setRequestProperty("content-type", "application/json;charset=utf-8"); // json格式發送數據
//        connection.setRequestProperty("content-type", "multipart/form-data; boundary=xxxxxxx"); // 表單數據發送
        
        // 必須設置setDoOutput為true才能向請求中寫數據,post請求必須設置true,如果是GET請求,下面前兩行可以省略
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); 
        connection.connect();
        
        // 獲取數據寫入流,如果是GET請求,這里不需要,因為GET請求不需要寫數據
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        bufferedWriter.write("name=xxx&age=18");
//        bufferedWriter.write("{\"name\":\"xxx\",\"age\":18}"); // json格式發送
        // 寫完數據一定要flush
        bufferedWriter.flush();
        bufferedWriter.close();
StringBuilder content
= new StringBuilder(); if (connection.getResponseCode() == 200) { // 獲取數據讀取流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String str; while ((str = bufferedReader.readLine()) != null) { content.append(str); } bufferedReader.close(); return content.toString(); } else { System.err.println(connection.getResponseCode()); } return ""; }

以上代碼,只要稍作調整,就可以完成GET POST PUT DELETE等http請求,非常簡單。

 

最后,貼出常用的請求最精簡代碼:

    /**
     * 發送get請求
     * @param url
     * @return
     * @throws Exception
     */
    public String get(String url) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        StringBuilder content = new StringBuilder();
        if (connection.getResponseCode() == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                content.append(str);
            }
            bufferedReader.close();
            return content.toString();
        } else {
            System.err.println(connection.getResponseCode());
        }
        return "";
    }
    
    /**
     * 發送post請求,請求參數為urlencode格式
     * @param url
     * @param params 類似 name=xxx&age=18
     * @return
     * @throws Exception
     */
    public String post(String url, String params) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.connect();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        bufferedWriter.write(params);
        bufferedWriter.flush();
        bufferedWriter.close();
        StringBuilder content = new StringBuilder();
        if (connection.getResponseCode() == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                content.append(str);
            }
            bufferedReader.close();
            return content.toString();
        } else {
            System.err.println(connection.getResponseCode());
        }
        return "";
    }
    
    /**
     * 發送post請求,請求參數為json格式
     * @param url
     * @param params 類似 {"name":"xxx","age":18}
     * @return
     * @throws Exception
     */
    public String postJson(String url, String params) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        connection.setRequestProperty("content-type", "application/json;charset=utf-8");
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.connect();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        bufferedWriter.write(params);
        bufferedWriter.flush();
        bufferedWriter.close();
        StringBuilder content = new StringBuilder();
        if (connection.getResponseCode() == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                content.append(str);
            }
            bufferedReader.close();
            return content.toString();
        } else {
            System.err.println(connection.getResponseCode());
        }
        return "";
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM