Skip to content
Advertisement

400 Bad request from Http request using java

I am following the “4. Java Socket Client Example: a HTTP Client” instruction from https://www.codejava.net/java-se/networking/java-socket-client-examples-tcp-ip in my Mac using IntelliJ.

The Http config is as easy as:

JavaScript

I copied the code without any change in the IntelliJ to test how would it work. However, after I did “java HttpClient.java” and “java HttpClient http://www.codejava.net/java-core” as indicated, what I got is:

JavaScript

I tried many solutions but none of them works for me. The only problem I found is that the HttpClient.class compiled with java version 11 missed lines of

JavaScript

then I changed java version to 1.8 it added the missing lines, but the error did not change. The interesting thing is, one of my friend doing the same thing in windows got everything as expected.

Any help would be appreciated.

Advertisement

Answer

The issue is how new lines are printed on Windows and Mac, Windows treats new lines as 2 characters, CR – Carriage return (“r”) + LF- Line feed (“n”) "rn", Mac prints new lines as LF("n") only. HTTP requests expects each line to be separated by CRLF "rn", what your code is printing is just "n" on Mac and "rn" on Windows that is why it works as expected on Windows platform.

To make it work on both Windows and Mac try the following code:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement