HTTP Error 400. The request has an invalid header name

19,513

Solution 1

For some reason, the DoAESEncrypt function was adding a carriage return "\r\n" to the Cipher text. This was removed and it worked fine.

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

Replace all \n and \r from your encrypted string which you passing to header as follow

strAuth.replace("\n","").replace("\r","")
Share:
19,513
Thomas
Author by

Thomas

Updated on June 04, 2022

Comments

  • Thomas
    Thomas almost 2 years

    I have a Java application with the below code. I am trying to invoke a REST web service using HttpClient POST. I need to send a custom header "auth" for authentication. The value of the header is the encrypted credentials separated by a ":".

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

    The DoAESEncrypt is a function that encrypts the input string and returns the Cipher. However, when I run this code, I get the below error where I have the statement client.execute:

    HTTP Error 400. The request has an invalid header name

    However, if I hard-code the below header with the encrypted Cipher I generated using the same DoAESEncrypt function, it works fine:

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