Http的認證(Authentication)機制可以用來保護非公開資源。如果Http伺服器開啟了認證,那麼使用者在發起請求時就需要攜帶使用者憑證。
Http的認證機制有:Digest認證、Client認證、Form Based認證等。目前Flutter的HttpClient只支援Basic和Digest兩種。這兩種認證方式最大的差別是傳送使用者憑證時,使用者憑證的內容,前者是通過Base64編碼,而後者是通過哈希運算。
httpClient.addCredentials(_uri,
"admin",
HttpClientBasicCredentials("username","password"),
);
httpClient.addCredentials(_uri,
"admin",
HttpClientDigestCredentials("username","password"),
);
HttpClient httpClient = HttpClient();//建立HttpClient
HttpClientRequest request = await httpClient.getUrl(uri);//開啟Http連接,設定請求頭
request.headers.add("user-agent", "test");//設定請求header
String payload="Hi";
request.add(utf8.encode(payload));
//request.addStream(_inputStream); //可以直接加入輸入流
HttpClientResponse response = await request.close();//等待連接伺服器
String responseBody = await response.transform(utf8.decoder).join();//讀取回應內容
httpClient.close();//請求結束
Http Method如httpClient.post()、httpClient.delete()等。 如果包含Query參數,可以在建置uri時添加,如:
Uri uri = Uri(scheme: "https", host: "xxx", queryParameters: {
"aa":"bb",
"cc":"dd"
});