在URLEncoded Http Post请求中保留+(加号)

问题描述 投票:0回答:3

我有这个功能,我用于登录请求。

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();
  }

如果密码中包含加号(+),则会将其编码为空格符号,然后请求将失败为凭据。我如何保留加号?我究竟做错了什么?

angular http urlencode
3个回答
3
投票

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

它会将原始+符号解释为空格的替代。

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

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);
}

然后使用它来正确编码:

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});

2
投票

在发送密码之前,只需使用encodeURIComponent对密码进行编码即可。

private login(params: LoginParams): Promise < any > {

  ...

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

  ...
}

注意:在API端,您必须使用decodeURIComponent(yourPasswordParam)来获取实际密码。

更新:

只需在这里尝试一下,看看它对编码的作用:

var encodedUsername = encodeURIComponent('mclovin+');
console.log('Encoding Username gives: ', encodedUsername);
console.log('NOT mclovin%252B');

var encodedPassword = encodeURIComponent('fogell+');
console.log('Encoding Password gives: ', encodedPassword);
console.log('NOT fogell%252B');

1
投票

如果您尝试将其作为URL的一部分发送,则必须使用encodeURIComponent对其进行编码。

看到您的代码,您将在HTTP参数中添加密码和用户名,这些密码和用户名将显示在请求网址中。

如果您不想将用户名和密码显示为url查询字符串的一部分,则可以将其作为http调用的请求正文发送,您将不需要执行encodeURIComponent

EX:console.log(encodeURIComponent('?x=test'));

console.log(encodeURIComponent('+test'));
© www.soinside.com 2019 - 2024. All rights reserved.