HttpURLConnection是什麼?

本文使用 HttpURLConnection 發送http請求(get、post)

URLConnection是個抽象類,它有兩個直接子類分別是HttpURLConnectionJarURLConnection。另外一個重要的類是URL,
通常URL可以通過傳給構造器一個String類型的參數來生成一個指向特定地址的URL實例
每個 HttpURLConnection 實例都可用於生成單個請求,但是其他實例可以透明地共享連接到 HTTP 服務器的基礎網絡。
請求後在 HttpURLConnection 的 InputStream 或 OutputStream 上調用 close() 方法可以釋放與此實例關聯的網絡資源,

但對共享的持久連接沒有任何影響。如果在調用 disconnect() 時持久連接空閒,則可能關閉基礎套接字。

JAVA使用HttpURLConnection發送POST數據是依靠OutputStream流的形式發送;具體編碼過程中,參數是以字符串“name=XXX”這種形式發送


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

/**
 *  功能說明:HttpClient - 通過發送Http請求獲取目標URL的數據
 */
public class TestURL {

    /** 提交方式POST **/
    public static final String SUBMIT_METHOD_POST = "POST";

    /** 提交方式GET **/
    public static final String SUBMIT_METHOD_GET = "GET";


    /**
     * 通過http請求獲取數據
     * @param urlStr	url地址,如:www.baidu.com
     * @param param		url的?後的參數,如:www.baidu.com?a=1&&b=2,則param爲"a=1&&b=2"
     * @return			返回讀取到的數據(json字符串)
     */
    public static String pub(String urlStr,String param,String method)
    {
        URL url = null;
        HttpURLConnection connection = null;
        StringBuffer buffer = new StringBuffer();
        System.out.println("request:"+urlStr+"?"+param);
        try {
            /*建立連接*/
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();

            /*設置連接屬性 */
            connection.setDoOutput(true);// 使用 URL 連接進行輸出   
            connection.setDoInput(true);// 使用 URL 連接進行輸入   
            connection.setUseCaches(false);// 忽略緩存   
            connection.setRequestMethod(method);// 設置URL請求方法   

            /*設置請求屬性*/
            connection.setRequestProperty("Content-Length",param.length()+"");
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.setRequestProperty("Connection", "Keep-Alive");// 維持長連接   
            connection.setRequestProperty("Charset", "UTF-8");// 設置編碼

            /*建立輸出流,並寫入數據*/
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(param.getBytes("UTF-8"));

            /*讀取數據*/
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        System.out.println("response:"+buffer.toString());
        return buffer.toString();
    }

    /*測試*/
    public static void main(String[] args) {   
        String urlStr="http://f.apiplus.cn/ssq.json";
        String param="a=1";
        pub(urlStr,param,SUBMIT_METHOD_POST);//地址就是:http://f.apiplus.cn/ssq.json?a=1
}}

輸出結果:即 代碼中的兩個 輸出 語句:

request: http://f.apiplus.cn/ssq.json?a=1

response: {"rows":5,"code":"ssq","info":"免費接口隨機延遲3-6分鐘,實時接口請訪問www.opencai.net查詢、購買或續費","data":[{"expect":"2018075","opencode":"07,09,12,13,22,24+11","opentime":"2018-07-01 21:18:20","opentimestamp":1530451100},{"expect":"2018074","opencode":"09,11,14,20,27,30+09","opentime":"2018-06-28 21:18:20","opentimestamp":1530191900},{"expect":"2018073","opencode":"02,09,14,15,16,23+10","opentime":"2018-06-26 21:18:20","opentimestamp":1530019100},{"expect":"2018072","opencode":"11,16,19,22,25,30+08","opentime":"2018-06-24 21:18:20","opentimestamp":1529846300},{"expect":"2018071","opencode":"02,05,06,13,16,19+03","opentime":"2018-06-21 21:18:20","opentimestamp":1529587100}]}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章