繁体   English   中英

Angular2 Http请求如何将body作为二进制返回?

[英]How Angular2 Http request can return body as binary?

我有一个url,用charset = iso-8859-7返回html内容,这意味着angulars http请求默认将数据转换为utf8,我无法正确地将它们编码回iso-8859-7。 经过大量的搜索,我发现很多人都有同样的问题,大多数答案都是为了改变服务器中的字符集,这是我无法做到的,因为服务器不属于我。

所以问题是HTTP请求如何返回二进制文件,以便我可以将它们编码为iso-8859-7字符串?

编辑 - 解决方案:
我最后做的是在RequestOptions上使用TextDecoder和{ responseType:ResponseContentType.ArrayBuffer }。 这是一个示例,可以帮助任何试图解析html页面并将其解码为正确编码的人。 希望能帮助所有在使用像Ionic2这样的Angular2的项目中尝试过这个的人。

public parser() {
    // Set content type
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded;'});
    // Create a request option, with withCredentials for sending previous stored cookies
    let options = new RequestOptions({
      withCredentials: true,
      headers: headers,
      responseType: ResponseContentType.ArrayBuffer
    });

    return this.http.get('https://blablablablabla', options) // ...using get request
      .map((res: any) => {

        var string = new TextDecoder('iso-8859-7').decode(res._body);

        var parser = new DOMParser();
        var htmlDoc = parser.parseFromString(string, "text/html");

        console.log(string)

        ..... blabla blabla doing some stuff here .....
      })
      .catch((error: any) => Observable.throw(error || 'Server error'));
}

发送请求时包括RequestOptionsArgs

RequestOptionsArgs指定字段responseType : ResponseContentType ResponseContentType.ArrayBufferResponseContentType.Blob

使用TextDecoder或类似的东西来解码结果。

查看文档:

https://angular.io/api/http/Http

https://angular.io/api/http/RequestOptions

https://angular.io/api/http/ResponseContentType

暂无
暂无

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

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