添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Why server returns response code 400(bad request)? (doesn't work)

URL serverAddress = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestMethod("POST");
int status = connection.getResponseCode(); // returns 400

For example this HTTP GET returns code 200: (works)

/** Creating Connection **/
 URL serverAddress = new URL(uri);
 HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
 connection.setRequestProperty("Content-Type", contentType);
 connection.setRequestMethod("GET");
 connection.setDoOutput(false);
 int status = connection.getResponseCode(); // returns 200

I've tried to get response code ( connection.getResponseCode() ) before I did actually wrote to a stream and close the stream ( writer.write() and os.close() ) thats why server returned Bad Request code(400). This is my code which works now:

            /** Creating Connection **/
            URL serverAddress = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestMethod("POST");
            /** POSTing **/
            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery());
            writer.flush();
            writer.close();
            os.close();
            connection.connect();
            int status = connection.getResponseCode();//this cannot be invoked before data stream is ready when performing HTTP POST
            PrinterClass.show(status);  //status
            if (status != 200)
                throw (new RESTfulWebServiceException("Invalid HTTP response status "
                    + "code " + status + " from web service server."));
private String getQuery() throws UnsupportedEncodingException
        JSONObject jobj = new JSONObject();
        jobj.put("customerNumber", new JSONString("003"));
        jobj.put("mappingCode", new JSONString("jac_003"));
        jobj.put("name", new JSONString("johnny"));
        jobj.put("status", new JSONString("ACTIVE"));
        PrinterClass.show(jobj.toString());
        return jobj.toString();
                Thanks, i also had the same issue and now it is fixed. can you explain why this happened?
– Rahul Raina
                Apr 10, 2016 at 19:23
                A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules (which is true in this example because POST was not defined).
– Jacob
                Apr 19, 2016 at 19:08

look into the documentation for the partner call. The get operation shows all partners, the post operation requires a body to be set. you dont send the body in your code, thus you send a bad request.

See here: http://nwb.sys.stage-cf-billing.swisslab.io/com.swisscom.nwb.cf.api/doc/swagger/index.html#!/Partner/GETPartner vs

http://nwb.sys.stage-cf-billing.swisslab.io/com.swisscom.nwb.cf.api/doc/swagger/index.html#!/Partner/POSTPartner

Thank you very much for your tip. Could you tell me how can I achieve that ? check my edit pls – Jacob Mar 26, 2015 at 16:05 I've added writer.write(json);and now everything works great. THANKS to thsts and gtklocker for your time !! – Jacob Mar 26, 2015 at 16:30 How can I get "response body" after POST request ?? its in json { msg: "someMSG" code: "BAD REQUEST" } connection.getInputStream() returns IOException connection.getResponseMessage() and connection.getResponseCode() works but its not enought information I need to print – Jacob Mar 31, 2015 at 16:57

Error 400 means Bad Request. You don't show us which URI you're trying to request, however it's quite possible that the URI accepts only GET requests and doesn't have a way to respond to a POST request, hence it throws a 400 error. For example, requesting a page that shows a listing of photos with GET makes sense, but making a POST request to said page makes no sense at all.

Another possibility is that you may be providing an incorrect content type. Usually, when making POST requests you want to use application/x-www-form-urlencoded, which is the content type that's used when you submit any web form on the internet. Furthermore, you may not be providing the form data that the server needs. Imagine a scenario where you try to post a message on Facebook but you've provided no message. The server will rightfully dismiss your empty request.

If you provide us with the request URI and content type you are using we can help you further in debugging this.

in both cases (post and get) I use: contentType="application/json" uri= "nwb.sys.stage-cf-billing.swisslab.io/com.swisscom.nwb.cf.api/v1/partner"documentation says that i can use POST – Jacob Mar 25, 2015 at 18:31 maybe im trying to get response code too early? (before the respond) . Are there any http programs so I can check if they can post? – Jacob Mar 25, 2015 at 22:45

For me, it was reading from the inputStream before I set the outputStream values for POST request. I moved the os.write()... section just below the OutputSteam os = ...

String body = "\"key\": \"value\"";
StringBuilder stringBuilder = new StringBuilder();
OutputStream os = conn.getOutputStream();
try {
    byte[] input = body.getBytes("utf-8");
    os.write(input, 0, input.length);           
} catch(Exception ex) {
    ex.printStackTrace();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))
try {
    String line = null;
    while ((line= br.readLine()) != null) {
        stringBuilder.append(line.trim());
} catch(Exception ex) {
    ex.printStackTrace();
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.