HTTP错误400.请求具有无效的标头名称

时间:2016-07-03 21:23:54

标签: java httpclient apache-httpclient-4.x

我有一个带有以下代码的Java应用程序。我试图使用HttpClient POST调用REST Web服务。我需要发送自定义标头“auth”进行身份验证。标头的值是由“:”分隔的加密凭证。

        String strAuth = DoAESEncrypt("userid:pwd");
        String strContent = DoAESEncrypt("{\"Name\":Tester,\"Id\":\"123\",\"NickName\":null,\"IsLocked\":false}");

          HttpClient client =  new DefaultHttpClient();          
          HttpPost post = new HttpPost("https://domainname/servicename");
          post.addHeader("auth",strAuth);
          post.addHeader("Content-Type", "application/json");
          StringEntity input = new StringEntity(strContent);
          post.setEntity(input);
          HttpResponse response = client.execute(post);

DoAESEncrypt是一个加密输入字符串并返回密码的函数。但是,当我运行此代码时,我得到以下错误,其中我有语句client.execute:

  

HTTP错误400.请求的标题名称无效

但是,如果我使用相同的DoAESEncrypt函数生成的加密密码对下面的标头进行硬编码,那么它可以正常工作:

      post.addHeader("auth","5PE7vNMYVFJT/tgYo7TGuPO05lqMQx5w3BAJKDS567A73vM0TYFmWO5tP=");

2 个答案:

答案 0 :(得分:2)

String strAuth = DoAESEncrypt("userid:pwd");
        String strContent = DoAESEncrypt("{\"Name\":Tester,\"Id\":\"123\",\"NickName\":null,\"IsLocked\":false}");

          HttpClient client =  new DefaultHttpClient();          
          HttpPost post = new HttpPost("https://domainname/servicename");
          post.addHeader("auth",strAuth.replace("\n","").replace("\r","");
          post.addHeader("Content-Type", "application/json");
          StringEntity input = new StringEntity(strContent);
          post.setEntity(input);
          HttpResponse response = client.execute(post);
  

将所有\ n和\ r \ n替换为您传递给的加密字符串   标题如下

strAuth.replace("\n","").replace("\r","")

答案 1 :(得分:1)

由于某种原因,DoAESEncrypt功能正在添加一个回车符" \ r \ n"到密文文本。这被删除,它工作正常。