Unable to write URLConnection due to doOutput

I asked a question here and I fixed my problem thanks to the user. This is the code I'm currently using.

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 to upload the record_file.txt file to a specific 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 information about this, and I added the following code immediately after declaring this rbc variable.

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

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

+4
source share
2 answers

The problem lies in this line:

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

To do this, you need to set doOutput to true . Here's how:

 URLConnection urlc = website.openConnection(); urlc.setDoOutput(true); WritableByteChannel rbc = Channels.newChannel(urlc.getOutputStream()); 
+15
source

I am a Java programmer and I have a different solution. Maybe it will be useful for someone. Just view advanced proxy settings in a web browser. System engineers in our company changed the proxy server settings, but I did not know about it. This mistake cost me 3 business days. I got this doOutput error while writing an ftp upload project in my company. I tried everything how to add conn.setDoOutput(true) or β€œfifty shades” of similar solutions, but did not save them. But after I changed the proxy settings to fix them, the error disappeared and now I can upload my files via ftp using urlConnection in java. I used the code in the link below to make the boot process, and added nothing except the host, port, user and password. http://www.ajaxapp.com/2009/02/21/a-simple-java-ftp-connection-file-download-and-upload/

0
source

Source: https://habr.com/ru/post/1494128/


All Articles