[英]HTTP/1.1 400 Bad Request in java HTTP post
I am trying to post xml data to API using HTTP post method with credentials but a getting HTTP/1.1 400 Bad Request error .. Can anyone pl help me out .... 我正在尝试使用具有证书的HTTP发布方法将xml数据发布到API,但收到HTTP / 1.1 400错误的请求错误..任何人都可以请我帮忙....
Here is my sample code: 这是我的示例代码:
BufferedReader br = new BufferedReader(new FileReader(new File("Data.xml")));
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
System.out.println("xml: "+sb);
params=sb.toString();
HttpPost request = new HttpPost("*****************url***************");
String urlaparam=URLEncoder.encode("importFormatCode:1&data:"+params,"UTF-8");
String userCredentials = "****:******";
byte[] auth = Base64.encodeBase64(userCredentials.getBytes());
StringEntity entity=new StringEntity(urlaparam);
request.addHeader("Content-type","application/x-www-form-urlencoded");
request.addHeader("Accept", "application/xml");
request.addHeader("Accept-Language", "en-US,en;q=0.5");
request.addHeader("Authorization", "Basic " + new String(auth));
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine());
System.out.println(request);
}
catch(Exception e)
{
}
First of all, your form parameters are not encoded correctly. 首先,您的表单参数编码不正确。 You are using colon (
:
) to separate keys from their values, but instead, the equal sign ( =
) must be used: 您使用的冒号(
:
),以从它们的值单独的键,而是等号( =
必须使用):
"importFormatCode:1&data:" + params
"importFormatCode:1&data:" + params
"importFormatCode=1&data=" + params
"importFormatCode=1&data=" + params
(See also W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded ) (另请参见W3C.org-HTML文档中的表单-application / x-www-form-urlencoded )
Apart from that, you must not URL-encode the entire string but only the keys and the values. 除此之外,您不能对整个字符串进行URL编码,而只能对键和值进行URL编码。 Otherwise you'll also encode the separator characters
=
and &
! 否则,您还将对分隔符
=
和&
进行编码。
The easiest way is to use the existing utility class org.apache.http.client.utils.URLEncodedUtils
(assuming that you're using Apache HTTP Components ): 最简单的方法是使用现有的实用程序类
org.apache.http.client.utils.URLEncodedUtils
(假设您使用的是Apache HTTP Components ):
String xmlData = // your xml data from somewhere
List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("importFormatCode", "1"),
new BasicNameValuePair("data", xmlData)
);
String body = URLEncodedUtils.format(params, encoding); // use encoding of request
StringEntity entity = new StringEntity(body);
// rest of your code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.