代码之家  ›  专栏  ›  技术社区  ›  Anjil Dhamala

在URL编码的Http Post请求中保留+(加号)

  •  0
  • Anjil Dhamala  · 技术社区  · 7 年前

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

    如果密码中有加号(+),则会将其编码为空格,然后请求失败,因为凭据不正确。如何保留加号?我做错了什么?

    3 回复  |  直到 7 年前
        1
  •  19
  •   MyNameIsTrez    4 年前

    这也是一个角度问题( @角度/公共/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
  •  3
  •   SiddAjmera    7 年前

    只用 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');
        3
  •  1
  •   nircraft    7 年前

    如果您试图将其作为URL的一部分发送,则必须使用 encodeURIComponent .

    看到您的代码,您正在HTTP参数中添加密码和用户名,该参数将显示在请求url中。

    如果不想将用户名和密码显示为url查询字符串的一部分,可以将其作为http调用的请求主体发送,而无需这样做 编码元件 .

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

    console.log(encodeURIComponent('+test'));
    推荐文章