java網絡請求GET和POST方式

GET方式

public static String readContentFromGet(String get_url) throws IOException { 


        String getURL = get_url;

        URL getUrl = new URL(getURL); 

        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); 

        connection.connect(); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

        String lines; 
        
        StringBuffer strbuff = new StringBuffer();
        
        while ((lines = reader.readLine()) != null) { 
                
            strbuff.append(lines);
            System.out.println(lines); 

        } 

        reader.close(); 

        connection.disconnect(); 

        return strbuff.toString();

    } 

POST方式

public static String readContentFromPost(String str) throws IOException {
        // Post請求的url,與get不同的是不需要帶參數
        URL postUrl = new URL(str);
        // 打開連接
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        // 設置是否向connection輸出,因爲這個是post請求,參數要放在
        // http正文內,因此需要設爲true
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        // Post 請求不能使用緩存
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        // 配置本次連接的Content-type,配置爲application/x-www-form-urlencoded的
        // 意思是正文是urlencoded編碼過的form參數,下面我們可以看到我們對正文內容使用URLEncoder.encode
        // 進行編碼
        connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); 
        // 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,
        // 要注意的是connection.getOutputStream會隱含的進行connect。
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        // The URL-encoded contend
        // 正文,正文內容其實跟get的URL中'?'後的參數字符串一致
        StringBuffer content = new StringBuffer();
        
        // DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫道流裏面
        out.writeBytes(content.toString()); 

        out.flush();
        out.close(); // flush and close
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        StringBuffer strbuff = new StringBuffer();
        
        while ((line = reader.readLine()) != null) {
            strbuff.append(line);
            System.out.println(line);
        }
        reader.close();
        connection.disconnect();
        return strbuff.toString();
    }


發佈了38 篇原創文章 · 獲贊 17 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章