Angular2 Http 请求如何以二进制形式返回正文? [英] How Angular2 Http request can return body as binary?

查看:19
本文介绍了Angular2 Http 请求如何以二进制形式返回正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a url that return the html content with charset=iso-8859-7 which means angulars http request convert the data to utf8 by default and i am unable to encode them back in iso-8859-7 properly. After a lot of searching i found out that many people had the same issue and most of the answers were to change the charset in the server, something that i'm unable to do as the server doesn't belong to me.

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

So the question is how can HTTP request return binary so i can encode them to iso-8859-7 string?

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

EDIT - SOLUTION:
What i finally did was to to use TextDecoder and {responseType: ResponseContentType.ArrayBuffer} at RequestOptions. Here is an example to help anyone who is trying to parse html pages and decode them into the right encoding. Hope to help all the guys who tried this in a project which is using Angular2 like Ionic2.

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.

中指定字段 responseType : ResponseContentTypeRequestOptionsArgs.(ResponseContentType.ArrayBufferResponseContentType.Blob)

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

Use TextDecoder or something similar to decode the result.

查看文档:

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

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

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

这篇关于Angular2 Http 请求如何以二进制形式返回正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆