Sur*_*ain 1 rest android http dart flutter
我有一个 REST API,当对其 URL 发出 GET 请求时,它会在其响应正文中提供图像。Postman 上给出的示例响应如下:\n
\n响应中的标头如下:
Date \xe2\x86\x92Fri, 24 Apr 2020 17:32:51 GMT\nServer \xe2\x86\x92WSGIServer/0.2 CPython/3.6.9\nContent-Type \xe2\x86\x92image/jpeg\nVary \xe2\x86\x92Accept, Cookie\nAllow \xe2\x86\x92GET, POST, HEAD, OPTIONS\nX-Frame-Options \xe2\x86\x92DENY\nContent-Length \xe2\x86\x92161076\nX-Content-Type-Options \xe2\x86\x92nosniff\nRun Code Online (Sandbox Code Playgroud)\n\n我尝试使用 flutter 代码向此 API 发出 GET 请求,然后打印响应中的正文内容(只是为了查看响应正文的外观。我不确定这是否是正确的方法)使用以下代码:
\n\nFuture<void> getImage() async {\n Directory directory = await getApplicationDocumentsDirectory();\n String filePath = "${directory.path}/loginCreds.txt";\n\n Map user_credentials = await this.getUserCreds(); //getUserCreds is another function in the same class\n String auth_token = user_credentials[\'auth_token\'];\n\n Response res = await get(\n "http://10.0.2.2:8000/usermgmt/profile/picture/",\n headers: {\n HttpHeaders.authorizationHeader: "Token $auth_token",\n },\n );\n print(\'\\n\\n\\n Image Response body\');\n print(res.body);\n print("\\n\\n\\n");\n }\nRun Code Online (Sandbox Code Playgroud)\n\n这给出了以下输出:
\n\nI/flutter (11120): \nI/flutter (11120): \nI/flutter (11120): \nI/flutter (11120): Image Response body:\nI/flutter (11120): \xc3\xbf\xc3\x98\xc3\xbf\xc3\xa0\nI/flutter (11120): \nI/flutter (11120): \nI/flutter (11120): \nRun Code Online (Sandbox Code Playgroud)\n\n如何从 GET 请求的响应中获取图像,并将其设置为 CircleAvatar 内的图像(在函数内build()使用)setState()getImage()使用)并将其保存在文件系统中?
恕我直言,你正在使用不好的方法。
Flutter 已经有几种通过 URL 获取图像的方法。对于您的CircleAvatar,您只需要做:
CircleAvatar(
backgroundImage: NetworkImage(
"http://10.0.2.2:8000/usr/profile/picture",
headers: {
"authorization": "Bearer $token",
// Other headers if wanted
},
),
)
Run Code Online (Sandbox Code Playgroud)
现在下载项目并将其保存在磁盘上是另一回事。
imageDownload(String url) async {
Response response = await get(url);
var documentDirectory = await getApplicationDocumentsDirectory();
var parent = documentDirectory.path + "/images";
var filePathAndName = "$parent/avatar.jpg"; // Build your image path here
await Directory(parent).create(recursive: true); // Make sure directories exist
File file2 = new File(filePathAndName);
file2.writeAsBytesSync(response.bodyBytes); // Use bodyBytes instead
}
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助!
| 归档时间: |
|
| 查看次数: |
3552 次 |
| 最近记录: |