is it possible to check the authentication status of an HTTP post request before getting the response?

StackOverflow https://stackoverflow.com/questions/17885863

Pregunta

I'm using java.net.HttpURLConnection.

I first write the body of the post request to the OutputStream associated with the URLConnection object.

After I have done that, I close the OutputStream and then call getInputStream() or getResponseCode() or getHeaderFields(). That's when I find out if the provided credentials were considered valid or not valid.

This is problematic, because I don't want to make the same post request again (and have to re-upload its contents, which could include large files) in the event that the user credentials were rejected for some reason.

Since an exception is thrown if there is an attempt to call getOutputStream() after getResponseCode() or getHeaderFields() have been called, how can I ensure that the user credentials were accepted before attempting to upload the data?

Is there a way around this or is it just the way the server is configured?

¿Fue útil?

Solución

The short answer is: You can't do that.

Basic auth is stateless. When you're doing a POST/PUT the user credentials are sent as headers for that HTTP request. They are not processed until the entire operation is complete (i.e. after you've sent the data payload).

In order to do what you're talking about you'd need to write a web service that managed login and file/data uploading separately through session management, allowing you to first authenticate (returning a session token of some sort) then send the data via a separate HTTP request.

Edit to add: In reality, you could hack your way around this by simply doing a GET to something that also requires auth. If it succeeds, you know the POST will also succeed baring the credentials being invalidated server side between the two requests. I would not advise this, but it would work.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top