简体   繁体   中英

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 ....

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:

  • Wrong: "importFormatCode:1&data:" + params
  • Correct: "importFormatCode=1&data=" + params

(See also W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded )

Apart from that, you must not URL-encode the entire string but only the keys and the values. 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 ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM