I am using java.net.HttpUrlConnection to make Http requests to my Server. I realized that if the Server return an error status (400 for example). HttpUrlConnection will throw an IOException corresponding to the error status.
My question is: Does HttpUrlConnection always throw an IOException if the server return an error status (4xx, 5xx)?
I take a look at HttpUrlConnection API description but I couldn't answer my question.
Updated: Please see my test:
public static void main(String[] args) {
try {
String url = "https://www.googleapis.com/oauth2/v3/userinfo?access_token=___fake_token";
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.getResponseCode();
conn.getInputStream();
} catch (Exception ex) {
ex.printStackTrace();
// Print IOException: java.io.IOException: Server returned HTTP response code: 401 for URL: https://www.googleapis.com/oauth2/v3/userinfo?access_token=abc
// If I commented conn.getResponseCode() -> The same IOException
}
}
Thank you!
Not if you check getResponseCode() before getInputStream() and the problem is an HTTP return code rather than a connect error.
Related
I try to use HttpURLConnection to send a post request to my local (xampp) server with an url like this http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2 , the server php file take param in url and send data to mysql database .
The url works fine on postman agent , and even another get method request works smooth in the android application .
Yet when i try the post method with following code :
public void postOrder() {
TextView tv = findViewById(R.id.tv1);
Thread t = new Thread( new Runnable() {
#Override
public void run() {
HttpURLConnection conn = null;
try {
String link = "http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2";
URL url = new URL(link);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(10000 /*ms*/);
conn.setConnectTimeout(15000 /*ms*/);
conn.connect();
}
catch (IOException e) {
Log.d("HTTP error: ", e.toString());
}
finally {
conn.disconnect();
}
}
} );
t.start();
}
It never sent the url and thus no data is stored to database .
And with 6 hours of trial and error , google and searching , i added this line of code :
InputStream is = conn.getInputStream();
And it finally works .
Please answer me why it only works after adding this line of code , what does it do ? I thought the url is triggered right after conn.connect();
Calling connect() only connects, but it doesn't send anything yet. Call getResponseCode() to force the request to be sent. That method is safer than getInputStream() which will throw an exception if the response is not a 2xx (in which case you'd need getErrorStream()).
I'm trying to send a http post request as part of a concurrent thread to an application launch.
The code below shows the current code I have now. I tried using the code from Baeldung and similar tutorial sites but I can't seem to get this working.
public static void main(String[] args) throws Exception {
HttpURLConnection con = (HttpURLConnection) new URL("http://localhost:5000/").openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setDoOutput(true);
String jsonInputString = "{\"status\": \"UP\"}";
OutputStream os = con.getOutputStream();
//random code here not involved with this quesiton
new Thread(new Runnable() {
public void run() {
while (true) {
try {
os.write(jsonInputString.getBytes());
os.flush();
}
catch (Exception exception) {
System.out.println("Its not working");
}
}
}
}).start();
launch(args);
When I go to type in localhost:5000 in a browser it says it can't connect.
First step make sure local host is working on port 5000, go to http://localhost:5000/ in a regular browser, if thats not working you need to make sure your machine is serving a page on port 5000 properly.
If thats working, the HTTP request may be getting blocked because its not connecting to a server with a valid SSL certificate, you can try changing the webpage to http://www.google.com and see if it gets a response.
I'm doing an Android app with an API with Python. The API is on a Google App Engine cloud and everything works fine when I tested it with Postman.
I'm trying to do a Login with a POST method. That method returns json with the user information I keep getting that error: FileNotFoundException
Here is some of my code:
try{
String account = params[0].get(0);
String password = params[0].get(1);
URL url = new URL("http", WEB_SERVICE_URL, PORT, REST_LOGIN);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
JSONObject json = jsonParser.serialJsonLogin(nomCompte, motPasse);
osw = new OutputStreamWriter(httpURLConnection.getOutputStream(),"UTF-8");
osw.write(json.toString());
osw.flush();
String body = readStream(httpURLConnection.getInputStream());
osw.close();
Log.i(TAG, "Return : " + body);
user = jsonParser.deserializeJsonUser(body);
}catch (Exception e) {
mException = e;
}finally {
if (mHttpURLConnection != null) {
mHttpURLConnection.disconnect();
}
}
return user;
At: String body = readStream(httpURLConnection.getInputStream()); I'm getting a java.io.FileNotFoundException: http://10.0.2.2:8080/login
My readStream method is fine, I tested it. If I look in my Google App Engine logs, I can see that there is no 404, or anything wrong. If I find the user I get a 201 if not a 403. So even if the error says FileNotFound, I see status code which means that actually the URL is right.
UPDATE: My API was giving me a 201 and getInputStream apparently doesn't work on 201 status. Changed my return status to 200 in my API and it works fine.
So far, I have this snippet.
URLConnection connection = null;
try {
connection = (new URL("some_link")).openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
} catch (IOException e) {
}
The possible response codes are 200 and 404 and it's working fine when the response code is 200 (OK). My question is how can I find the response code received by my connection, for example: if the response code is 404, throw an exception and do smth there.
use something like this:
HttpURLConnection connection = (HttpURLConnection)new URL("URL_STRING")
.openConnection();
int statusCode = connection.getResponseCode();
Make it to a type of HTTPUrlConnection. Then you can use .getResponseCode();
Hello all in my doe I have a try catch and I am catching the exception from a webservice
However If I run my web service in Firefox Poster add-on I get a response as well as a stastus exception
This obviously is not ALL the code but basically the exception is happening at getInputStream()
How can I get the response from the exception?
try{
//Get Response
stream = connection.getInputStream();
} catch (Exception e) {
throw new CustomException("Exception - " + e.getMessage());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int code = connection.getResponseCode();
String msg = connection.getResponseMessage();
These methods will still throw IOException if you can't reach the server. But if the server responds, even with an error, these methods give you access to the response.