1
votes

I have a java code which does a http post request to a nodejs server. The nodejs server executes its code for the request correct and sends response back. However the java code is receiving Http response code 400.

Here is what my java code looks like:

protected String httpPostRequest(URL postUrl, byte[] fields, String requestType) {
        try {
            HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", requestType);
            conn.setRequestProperty("Content-Length", String.valueOf(fields.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(fields);
            Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (int c; (c = in.read()) >= 0;)
                sb.append((char) c);
            return sb.toString();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e){
            //e.printStackTrace();
        }
        return "";
    }

And here is how the nodejs code looks like:

app.post("/test", function(req, res){
    res.send("File Created");
    //res.status(200)
    res.end();
});

I have tried res.status(200).send("something"), res.send("something"), res.send("something").end(); But I am still getting response code 400.

EDIT: detailed error:

java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:3000/test
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
    at controller.utils.http.AbstractHttpClient.httpPostRequest(AbstractHttpClient.java:30)
    at controller.utils.http.HttpClient.callExternalUrl(HttpClient.java:35)
    at model.Project.<init>(Project.java:103)
    at controller.ProjectController.createProject(ProjectController.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at controller.AbstractApplicantzController.processRequest(AbstractApplicantzController.java:114)
    at view.AbstractWebApi.doRequestAction(AbstractWebApi.java:206)
    at view.AbstractWebApi.processRequest(AbstractWebApi.java:189)
    at view.AbstractWebApi.doPost(AbstractWebApi.java:66)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
4
Yeah, that was just a mistake while pasting the error, i updated the error. I have handler for "/" and "/test" both and a few others and all of them return 400d_void
Have you the same problem with a simple GET request on the same URI ?Daphoque
@Daphoque No Get request is working without errors.d_void
Ok, according to this the problem comes from your post data, check again your flow and verify the content type, the encoding and the way you're writing your datasDaphoque
@Daphoque - Yes i think you are correct let me try a few options and see if it is fixedd_void

4 Answers

0
votes

You should not be setting the Content-Length header yourself. The error is happening because the value of Content-Length is wrong.

Java will buffer whatever you are sending for you and set this value for you. Don't try to set it yourself. Removing this line should make it work:

javaconn.setRequestProperty("Content-Length", String.valueOf(fields.length));
0
votes

I've had something similar, especially with POST requests. From Postman, try to hit the endpoint with a trailing '/' and without it. If you get the same 400 response on the one without the trailing slash then you just need to make sure that either your Java code adds it before sending, or your Node code does so before routing.

0
votes

The code you posted working fine for me in JDK1.8.0_191 and Node v10.15.3 It looks like you have problem in your node server Check your express server code

0
votes

With the new specification HTTPbis, there are extended definitions of some statuses. HTTP 400 now refers not only to the incorrect form of the request but also to the capacity of the server to process it. As stated here:

The 400 (Bad Request) status code indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.

So probably your request cannot be processed from your node server due to the load on the request. Try to POST just a simple "Hello World" and it should work.