0

What am I doing wrong? Please have a look at code.

HttpURLConnection conn = (HttpURLConnection) new URL(http_url).openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
/*
java.io.IOException: Server returned HTTP response code: 400 for URL: http_url
  at sun.net.www.protocol.http.HttpURLConnection.getInputStream
*/

If I open the http_url in browser, it's working.

2
  • See alvinalexander.com/blog/post/java/… Commented Dec 13, 2016 at 13:01
  • I was confused since I was getting the Java error instead of the error payload. Later when I checked the http_url in postman, it showed the error payload as well as response code 400. Actually I should have used conn.getErrorStream() in case of response code >= 400. Commented Dec 26, 2016 at 5:55

3 Answers 3

1

You are not connected (next code from http://alvinalexander.com/blog/post/java/how-open-url-read-contents-httpurl-connection-java).

 HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      // just want to do an HTTP GET here
      connection.setRequestMethod("GET");

      // uncomment this if you want to write output to this url
      //connection.setDoOutput(true);

      // give it 15 seconds to respond
      connection.setReadTimeout(15*1000);
      connection.connect();

      // read the output from the server
      reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
Sign up to request clarification or add additional context in comments.

Comments

1

I was confused since I was getting the Java error instead of the error payload. Later when I checked the http_url in postman, it showed the error payload as well as response code 400. Browser doesn't show response code if payload is available. Actually I should have used conn.getErrorStream() instead of conn.getInputStream() in case of response code >= 400.

Comments

0

You have to follow HTTP protocol, and set all HTTP headers server expects to get before reading a response. Definitely you missed one or more headers, like content-type, accept etc. also maybe server does not like Java agent header and likes agents from IE, Chrome, Firefox etc. So server is right, you request is bad :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.