1. 程式人生 > 實用技巧 >java.net.URL

java.net.URL

說明

  • URLConnection
  • HttpURLConnection extends URLConnection

Demo 請求API,不用傳送引數

// 目標地址
URL url = new URL("https://api")
// 轉換
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection()
// 設定請求方法
urlConnection.setRequestMethod("GET")
// 從此連結開啟一個輸入流,讀取介面返回的資料,input到我們的記憶體中。
urlConnection.inputStream.withReader("UTF-8", {
    Reader reader -> println(reader.text) }
)

Demo 請求API,傳送引數

URL baseUrl = new URL('https://api/')
HttpURLConnection connection = (HttpURLConnection)baseUrl.openConnection()
// 設定請求方法
connection.setRequestMethod("POST")
// 設定需要輸出引數給對方
connection.setDoOutput(true)
// 設定請求輸出引數型別
connection.setRequestProperty("Content-Type","application/json")
// 輸出給對方引數
connection.outputStream.withWriter { java.io.Writer writer -> writer << params}
// 接受返回內容
filebyte = connection.inputStream.getBytes()

理解

URL baseUrl = new URL("http://www.duchaoqun.cn")
HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection()
connection.setRequestMethod("GET")
connection.setDoInput(true)
def fileBytes = connection.inputStream.getBytes()
GET/POST請求,不需要引數時,當我們需要通過這個URL連線從伺服器獲取資料到本地記憶體,就要設定DoInput為true(預設為true)。
connection.setDoOutput(true)
connection.outputStream.withWriter {...}
POST請求,需要引數時,我們要從記憶體給遠端一些引數,就需要設定DoOutput為true(預設為false),然後給它輸出一些引數。