Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem writing to http URL with PUT (and HttpURLConnection)!

 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the code below. While it creates the "out.txt" file, it won't write any data and returns a 204 "No Content" response. Any idea what's wrong?

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The response code isn't available until after you've sent the content.



By asking for the response code before you send the content, you're forcing HttpUrlConnection to terminate the request to force the server to send one. Don't ask for the response until after your request is complete.
 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes!

That was it, thanks!

One question, though: why is Http set up that way so that even if you aren't allowed to write to a stream, you still have to wait till after spending all that processing time writing out the bytes of a file before you can find that out?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, HTTP was designed as a very simple request/response protocol. So the client sends everything they're going to send, and then the server sends everything they're going to send. Originally, that was always done in a separate network connection -- i.e., one request, one response per connection, by definition. This makes it possible for the client to be completely "dumb" -- a request can come out of a file, and a response go into a file, without the client doing any interpretation whatsoever.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic