我想对来自Angular 4应用程序的API项目的传出POST和PUT JSON请求使用gzip或deflate压缩。
目前,我正在使用HttpClient发送请求。我尝试使用pako或zlib生成压缩内容,但服务器返回响应,指示压缩算法的实现不良。
我的POST TypeScript如下所示:
public post(url: string, content: any): Observable < any > {
const fullUrl: string = `${HttpService.baseUrl}/${url}`;
Logger.debug(`Beginning HttpPost invoke to ${fullUrl}`, content);
// Optionally, deflate the input
const toSend: any = HttpService.compressInputIfNeeded(content);
return Observable.create((obs: Observer < any > ) => {
this.client.post(fullUrl, toSend, HttpService.getClientOptions()).subscribe(
(r: any) => {
Logger.debug(`HttpPost operation to ${fullUrl} completed`, r);
// Send the response along to the invoker
obs.next(r);
obs.complete();
},
(err: any) => {
Logger.error(`Error on HttpPost invoke to ${fullUrl}`, err);
// Pass the error along to the client observer
obs.error(err);
}
);
});
}
private static getClientOptions(): {
headers: HttpHeaders
} {
return {
headers: HttpService.getContentHeaders()
};
}
private static getContentHeaders(): HttpHeaders {
let headers: HttpHeaders = new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8'
});
// Headers are immutable, so any set operation needs to set our reference
if (HttpService.deflate) {
headers = headers.set('Content-Encoding', 'deflate');
}
if (HttpService.gzip) {
headers = headers.set('Content-Encoding', 'gzip');
}
return headers;
}
private static compressInputIfNeeded(content: any): string {
const json: string = JSON.stringify(content);
Logger.debug('Pako Content', pako);
if (HttpService.deflate) {
const deflated: string = pako.deflate(json);
Logger.debug(`Deflated content`, deflated);
return deflated;
}
if (HttpService.gzip) {
const zipped: string = pako.gzip(json);
Logger.debug(`Zipped content`, zipped);
return zipped;
}
return json;
}
我已经尝试了各种放松和压缩内容的排列,但似乎没有任何效果。我还检查了Fiddler中的传出请求并验证了Fiddler无法解释请求JSON。
我还验证了内容与Content-Type:application / json一起发送; charset = UTF-8和Content-Encoding:使用适当的Accept-Encoding值进行收缩。
在这一点上,我确信我要么做错了我还没弄明白,或者我想做的事情比HttpClient允许我做的更多。
我刚刚自己开始工作了。
我认为问题可能是你使用pako
的方式。
除非您明确传递该选项,否则pako.gzip(obj)
不会返回字符串。它返回一个字节数组。 (特别是Uint8Array
)
默认的HttpClient
会尝试将其转换为json字符串,这是错误的。我做了以下事情:
const newHeaders: Headers = new Headers();
newHeaders.append('Content-Encoding', 'gzip')
newHeaders.set('Content-Type', 'application/octet-stream');
var options = { headers: newHeaders, responseType: ResponseContentType.Json };
var compressedBody = pako.gzip(JSON.stringify(body))
client.post(url, compressedBody.buffer, options);
请注意以下几点:
Content-Type
和Content-Encoding
标头。您不必自己压缩任何东西,只需设置适当的标题,浏览器使用与服务器的协商过程自动执行此操作,如果服务器支持gzip编码,则浏览器将发送编码请求。