java HTTP 错误 400。请求的标头名称无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38174460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTTP Error 400. The request has an invalid header name
提问by Thomas
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 ":".
我有一个带有以下代码的 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);
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:
DoAESEncrypt 是一个加密输入字符串并返回密码的函数。但是,当我运行此代码时,出现以下错误,其中包含语句 client.execute:
HTTP Error 400. The request has an invalid header name
HTTP 错误 400。请求的标头名称无效
However, if I hard-code the below header with the encrypted Cipher I generated using the same DoAESEncrypt function, it works fine:
但是,如果我使用相同的 DoAESEncrypt 函数生成的加密密码对以下标头进行硬编码,则它可以正常工作:
post.addHeader("auth","5PE7vNMYVFJT/tgYo7TGuPO05lqMQx5w3BAJKDS567A73vM0TYFmWO5tP=");
回答by Aman
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
从您传递给标头的加密字符串中替换所有 \n 和 \r,如下所示
strAuth.replace("\n","").replace("\r","")
回答by Thomas
For some reason, the DoAESEncrypt function was adding a carriage return "\r\n" to the Cipher text. This was removed and it worked fine.
出于某种原因,DoAESEncrypt 函数在密码文本中添加了回车“\r\n”。这已被删除,并且工作正常。