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

Ram*_*bou 4 encoding http character-encoding ionic2 angular

我有一个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'));
}
Run Code Online (Sandbox Code Playgroud)

csh*_*shu 5

包括RequestOptionsArgs发送请求的时间.

在responseType : ResponseContentType里面指定字段RequestOptionsArgs.(ResponseContentType.ArrayBuffer或者ResponseContentType.Blob)

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

查看文档:

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

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

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