Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot write URLConnection because of doOutput

Tags:

java

I've asked a question here and I've fixed my problem thanks to an user. This is the code I am using at the moment.

void UploadToDatabase() throws MalformedURLException, IOException {
          URL website = new URL("http://mk7vrlist.altervista.org/databases/record_file.txt");
          WritableByteChannel rbc = Channels.newChannel(website.openConnection().getOutputStream());

          FileOutputStream fos;
          fos = new FileOutputStream("record_file.txt");
          fos.getChannel().transferTo(0, Long.MAX_VALUE, rbc);
          fos.close();
     }

My goal is upload the file record_file.txt on a particular web link as you can see above. However, when I try to run this code, NetBeans gives me this error:

java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)

I read some stuff about this and I added the following code just after the declaration of that rbc variable.

 URLConnection urlc = website.openConnection();
 urlc.setDoOutput(true);

By the way, I always have the same error. Could you help me?

like image 653
Alberto Miola Avatar asked Jul 29 '13 19:07

Alberto Miola


2 Answers

The problem lies on this line:

WritableByteChannel rbc = Channels.newChannel(website.openConnection().getOutputStream());

You will need to set doOutput to true for this to work. Here's how:

URLConnection urlc = website.openConnection();
urlc.setDoOutput(true);
WritableByteChannel rbc = Channels.newChannel(urlc.getOutputStream());
like image 168
tbodt Avatar answered Nov 16 '22 20:11

tbodt


For me it was due to incorrect way of using header, like

HttpEntity<String> entity = new HttpEntity("parameters", headers); //Issue was here

I just made as

 HttpEntity<String> entity = new HttpEntity(headers); //Fixed Issue

check here other details

like image 22
Kundan Atre Avatar answered Nov 16 '22 21:11

Kundan Atre