我有一个用于登录请求的函数。
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/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});
发送密码前只需使用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');
如果您试图将其作为URL的一部分发送,则必须使用encodeURIComponent
进行编码。
看到你的代码,你正在HTTP参数中添加密码和用户名,这些参数将显示在请求url中。
如果您不想将用户名和密码显示为url查询字符串的一部分,您可以将其作为http调用的请求主体发送,而无需执行encodeURIComponent
。
例如:console.log(encodeURIComponent('?x=test'));
console.log(encodeURIComponent('+test'));