2017-04-02 93 views
2

我有一個url返回html內容charset = iso-8859-7這意味着angulars http請求將數據默認轉換爲utf8,我無法正確地將它們編碼回iso-8859-7。經過大量搜索後,我發現許多人遇到同樣的問題,大部分答案都是要更改服務器中的字符集,這是我無法做到的,因爲服務器不屬於我。Angular2 Http請求如何以二進制形式返回body?

所以問題是如何HTTP請求返回二進制,所以我可以將它們編碼爲iso-8859-7字符串?

編輯 - 解決方案:
我終於做是使用TextDecoder和{的responseType:ResponseContentType.ArrayBuffer}在RequestOptions。這裏有一個例子可以幫助任何試圖解析html頁面並將它們解碼爲正確編碼的人。希望能夠幫助所有在使用Angular2的項目中嘗試過這樣的人,比如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')); 
} 
+2

您的要求,請張貼細節,包括你正在使用 – Gary

+0

什麼@Gary說,任何頭。 –

+0

如果使用['response.arrayBuffer()'](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)會發生什麼? –

回答

2

發送請求時包含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

+0

Yeap,像一個魅力工作!和TextDecoder也做了這份工作! – Rambou