[英]How to call web services on Rikulo's dart stream server?
嘗試在Stream服務器上使用靜態Web服務時遇到技術問題。
我使用HTTPClient.openUrl從另一個遠程服務器檢索JSON響應,但是一旦打開連接,就無法再將響應(connect.response.write)寫入我的瀏覽器客戶端。
該錯誤列出如下:
Unhandled exception:
Bad state: StreamSink is closed
#0 _FutureImpl._scheduleUnhandledError.<anonymous closure> (dart:async:325:9)
#1 Timer.run.<anonymous closure> (dart:async:2251:21)
#2 Timer.run.<anonymous closure> (dart:async:2259:13)
#3 Timer.Timer.<anonymous closure> (dart:async-patch:15:15)
#4 _Timer._createTimerHandler._handleTimeout (dart:io:6730:28)
#5 _Timer._createTimerHandler._handleTimeout (dart:io:6738:7)
#6 _Timer._createTimerHandler.<anonymous closure> (dart:io:6746:23)
#7 _ReceivePortImpl._handleMessage (dart:isolate-patch:81:92)
有人知道在流服務器上調用Web服務的正確方法嗎?
關鍵是您必須返回Future,因為您的任務(openUrl)是異步的。 在示例代碼中,您必須執行以下操作:
return conn.then((HttpClientRequest request) {
//^-- notice: you must return a future to indicate when the serving is done
有關更多信息,請參閱請求處理 。 為避免這種錯誤,我在此處發布了功能請求 。
這是一個工作示例:
library issues;
import "dart:io";
import "dart:uri";
import "package:rikulo_commons/io.dart" show IOUtil;
import "package:stream/stream.dart";
void main() {
new StreamServer(uriMapping: {
"/": (connect)
=> new HttpClient().getUrl(new Uri("http://google.com"))
.then((req) => req.close())
.then((res) => IOUtil.readAsString(res))
.then((result) {
connect.response.write(result);
})
}).start();
}
這是我的原始代碼:
void startProcess(HttpConnect connect){
String method = "GET";
String url = "http://XXXXXX/activiti-rest/service/deployments";
Map authentication = {"username":"XXXXX", "password":"XXXXX"};
Map body = {"XXXXX":"XXXXX", "XXXXX":"XXXXX"};
processRequest(connect, method, url, authentication, body.toString());
}
void processRequest(HttpConnect connect, String method, String url, Map authentication, String body) {
HttpClient client = new HttpClient();
Uri requestUri = Uri.parse(url);
Future<HttpClientRequest> conn = client.openUrl(method, requestUri);
conn.then((HttpClientRequest request) {
request.headers.add(HttpHeaders.CONTENT_TYPE, Constants.CONTENT_TYPE_JSON);
// Add base64 authentication header, the class is contained in a separate dart file
String base64 = Base64String.encode('${authentication["username"]}:${authentication["password"]}');
base64 = 'Basic $base64';
request.headers.add("Authorization", base64);
switch( method ) {
case Constants.METHOD_GET: break;
case Constants.METHOD_POST:
body = body.replaceAllMapped(new RegExp(r'\b\w+\b'), (match) => '"${match.group(0)}"' );//no replacement for now
request.write(body);
break;
}
return request.close();
})
.then((HttpClientResponse response) {
return IOUtil.readAsString(response);
})
.then((String result) {
connect.response.write(result);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.