Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

angular - How Angular2 Http request can return body as binary?

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.

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

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'));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Include the RequestOptionsArgs when you send request.

Specify the field responseType : ResponseContentType inside RequestOptionsArgs. (Either ResponseContentType.ArrayBuffer or ResponseContentType.Blob)

Use TextDecoder or something similar to decode the result.

See the docs:

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...