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.
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()));
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.
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 :-)
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.