如何在Flutter中将标题传递到URL

hmmo2u0o  于 2022-11-25  发布在  Flutter
关注(0)|答案(1)|浏览(133)

我有一个关于如何从URL查看PDF的问题。我正在使用flutter_pdfview库,我尝试从URL获取PDF并在Flutter应用程序中查看。问题是我的URL只能通过令牌访问(会话ID/报头),但我不知道如何通过考试,因为我现在的方式不适合。以下是flutter_pdfview库的所有者如何从URL获取PDF的示例(无标题):https://github.com/endigo/flutter_pdfview/blob/master/example/lib/main.dart#L49
下面是我的代码,我不知道如何传递头文件,而不是像这样:

Future<File> createFileOfPdfUrl() async {
    Completer<File> completer = Completer();

    if (kDebugMode) {
      print("Start download file from internet!");
    }
    try {
      String url =
          "$customURL.pdf";
      if (kDebugMode) {
        print("url: $url");
      }

      final filename = url.substring(url.lastIndexOf("/") + 1);
      var client = HttpClient();
      HttpClientRequest request = await client.getUrl(Uri.parse(url));
      request.headers.add(
          HttpHeaders.acceptHeader,
          HeaderValue(
              "text/plain", {'APPAUTH': '${widget.authService.loginToken}'})); // this method doesn't seems to work for me. I'm getting an empty PDF.

      var response = await request.close();
      var bytes = await consolidateHttpClientResponseBytes(response);
      var dir = await getApplicationDocumentsDirectory();

      if (kDebugMode) {
        print("Download files");
        print("${dir.path}/$filename");
      }
      File file = File("${dir.path}/$filename");

      await file.writeAsBytes(bytes, flush: true);
      completer.complete(file);
    } catch (e) {
      throw Exception('Error parsing asset file!');
    }

    return completer.future;
  }
uqxowvwt

uqxowvwt1#

请勿执行此操作:

request.headers.add(
          HttpHeaders.acceptHeader, // here is the problem
          HeaderValue(
              "text/plain", {'APPAUTH': '${widget.authService.loginToken}'}));

我的解决方案:

request.headers.add("APPAUTH", "12345abcde67890defgh");

由于某种原因,如果您提供了一个HeaderValue,您还需要在它之前提供一个字符串值,它可以是HttpHeaders.acceptHeaderHttpHeaders.serverHeader等。我尝试了该枚举列表中的许多方法,但没有一种方法对我有效,因此我使用了上述解决方案,其中您不需要传递HttpHeader值类型。

相关问题