httpURLConnection-網路請求的兩種方式-get請求和post請求

來源:互聯網
上載者:User

標籤:

GET請求

 

 /**     * 從網路擷取json資料,(String byte[})
*
@param path * @return */ public static String getJsonByInternet(String path){ try { URL url = new URL(path.trim()); //開啟串連 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if(200 == urlConnection.getResponseCode()){ //得到輸入資料流 InputStream is =urlConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while(-1 != (len = is.read(buffer))){ baos.write(buffer,0,len); baos.flush(); } return baos.toString("utf-8"); } } catch (IOException e) { e.printStackTrace(); } return null; }
POST請求

 

 

//擷取其他頁面的資料    /**     * POST請求擷取資料     */    public static String postDownloadJson(String path,String post){        URL url = null;        try {            url = new URL(path);            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            httpURLConnection.setRequestMethod("POST");// 提交模式            // conn.setConnectTimeout(10000);//連線逾時 單位毫秒            // conn.setReadTimeout(2000);//讀取逾時 單位毫秒            // 發送POST請求必須設定如下兩行            httpURLConnection.setDoOutput(true);            httpURLConnection.setDoInput(true);            // 擷取URLConnection對象對應的輸出資料流            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());            // 發送請求參數            printWriter.write(post);//post的參數 xx=xx&yy=yy            // flush輸出資料流的緩衝            printWriter.flush();            //開始擷取資料            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());            ByteArrayOutputStream bos = new ByteArrayOutputStream();            int len;            byte[] arr = new byte[1024];            while((len=bis.read(arr))!= -1){                bos.write(arr,0,len);                bos.flush();            }            bos.close();            return bos.toString("utf-8");        } catch (Exception e) {            e.printStackTrace();        }        return null;    }

 

httpURLConnection-網路請求的兩種方式-get請求和post請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.