java HTTP帖子中的HTTP / 1.1 400错误请求

时间:2014-06-02 10:26:22

标签: java http post

我正在尝试使用带有凭据的HTTP post方法将xml数据发布到API,但是获取HTTP / 1.1 400 Bad Request错误..任何人都可以帮助我....

以下是我的示例代码:

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)
{
}

1 个答案:

答案 0 :(得分:1)

首先,您的表单参数未正确编码。您使用冒号(:)将键与其值分开,但必须使用等号(=):

  • 错误:"importFormatCode:1&data:" + params
  • 正确:"importFormatCode=1&data=" + params

(另见W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded

除此之外,您不能对整个字符串进行URL编码,只能对键和值进行URL编码。否则,您还会对分隔符=&进行编码!

最简单的方法是使用现有的实用程序类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