简体   繁体   English

通过 http 发送 byte[]

[英]Send byte[] over http

I do have get request over http from an angular based client side which expects as an answer an array of bytes from a java server .我确实从基于 angular 的客户端通过http获取请求,该请求期望来自 java服务器的字节数组作为答案。

angular.ts angular.ts

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

controller.java控制器.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;
        }

Parsing error is encountered while transmitting over http: "HttpErrorResponse":通过 http 传输时遇到解析错误:“HttpErrorResponse”:

  • message : 'Http failure during parsing for http://localhost ...'消息'解析http://localhost 时Http 失败......'
  • error : 'error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad'错误'错误:SyntaxError:JSON.parse()在XMLHttpRequest.onLoad的位置0处的JSON中的意外标记%'

Any ideas why this is happening?任何想法为什么会发生这种情况?

It's happening because you call the overload of get() that takes a generic parameter:发生这种情况是因为您调用了带泛型参数的get()重载:

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

This overload sets the response type to JSON, thus telling the HttpClient to parse the response body to JSON and to returned the generated object or array.此重载将响应类型设置为 JSON,从而告诉 HttpClient 将响应正文解析为 JSON 并返回生成的对象或数组。 Since you do not want to receive JSON, you must use another overload.由于您不想接收 JSON,因此必须使用另一个重载。

The documentation is your friend.文档是您的朋友。

If you want to receive a Blob, for example, you would use the second overload, documented as returning an Observable<Blob> , and expecting options with responseType: 'blob' .例如,如果你想接收一个 Blob,你可以使用第二个重载,记录为返回一个Observable<Blob> ,并期待带有responseType: 'blob'选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM