本文介绍了在URLEncoded Http Post请求中保留+(加号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有用于登录请求的功能.

I have this function that I use for login requests.

private login(params: LoginParams): Promise<any> {
    const loginHeaders: HttpHeaders = new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
        .set('site', 'first');

    const loginCredentials = new HttpParams()
        .set('j_username', params.username)
        .set('j_password', params.password);

    const requestUrl = this.appConfig.baseUrl + 'restoftheurl';

    return this.http
        .post(requestUrl, loginCredentials.toString(),
            {headers: loginHeaders, responseType: 'text'})
        .toPromise();
  }

如果密码中带有加号(+),则将其编码为空格符号,然后该请求将成为错误的凭据,失败.如何保留加号?我在做什么错了?

If the password has a plus sign (+) in it, it is encoded into a space sign and then the request fails being a bad credential. How do I preserve the plus sign? What am I doing wrong?

推荐答案

这也是一个Angular问题( @ angular/common/http )

This is also an Angular issue (@angular/common/http)

它将解释原始的 + 符号代替空格.

It will interpret the raw + sign as a replacement for a space.

您可以将 HttpParameterCodec 实现为简单的编码器,例如:

You can implement HttpParameterCodec into a simple encoder, for example:

import {HttpParameterCodec} from "@angular/common/http";
export class HttpUrlEncodingCodec implements HttpParameterCodec {
    encodeKey(k: string): string { return standardEncoding(k); }
    encodeValue(v: string): string { return standardEncoding(v); }
    decodeKey(k: string): string { return decodeURIComponent(k); }
    decodeValue(v: string) { return decodeURIComponent(v); }
}
function standardEncoding(v: string): string {
    return encodeURIComponent(v);
}

然后使用它进行正确编码:

And then use it to get encoded correctly:

const headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'});
const params = new HttpParams({encoder: new HttpUrlEncodingCodec()});
http.post(url, params, {headers: this.headers});

这篇关于在URLEncoded Http Post请求中保留+(加号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 04:37