【问题标题】:Send byte[] over http通过 http 发送 byte[]
【发布时间】:2019-12-20 12:41:59
【问题描述】:

我确实从基于角度的 client 端通过 http 发出 get 请求,该请求期望来自 java 的字节数组作为答案 服务器。

angular.ts

  downloadDocument(documentId: string) {
    const params = new HttpParams().set('docId', documentId);
    return this.httpClient.get<any>(`/downloadpdf/`,
      { params: params});
  }

controller.java

     @GetMapping("/downloadpdf")
        public String downloadDocument(@RequestParam("docId") final String docId) {
            String response = (new String(getBytesArray(docId)));
            // getBytesArray returns a byte[]
            // response correctly computed
            return response;
        }

通过http传输时遇到解析错误: “HttpErrorResponse”:

  • 消息'解析http://localhost时的Http失败...'
  • 错误'错误:SyntaxError:在 XMLHttpRequest.onLoad 的 JSON.parse () 位置 0 处的 JSON 中的意外标记 %'

任何想法为什么会发生这种情况?

【问题讨论】:

  • 我在谷歌上看到了错误消息,您的回复似乎不是有效的 JSON 格式。至于为什么会这样,我不太确定

标签: java angular file http byte


【解决方案1】:

这是因为您调用了带有泛型参数的get() 的重载:

this.httpClient.get<any>(...)

此重载将响应类型设置为 JSON,从而告诉 HttpClient 将响应正文解析为 JSON 并返回生成的对象或数组。由于您不想接收 JSON,因此必须使用另一个重载。

The documentation 是你的朋友。

例如,如果您想接收 Blob,您将使用第二个重载,记录为返回 Observable&lt;Blob&gt;,并期望带有 responseType: 'blob' 的选项。

【讨论】:

    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    相关资源
    最近更新 更多