I am trying to upload a file using PUT method. I have been advised before to use POST and do a multipart upload but my web service only allows GET, PUT, PATCH, DELETE, HEAD and OPTIONS. And the main reason for that is that I am updating the JSON array that contains id, target, source, file. Now I just have to update the file part in the web service i.e. I have to upload the file there.
Here is my code:
URLConnection urlconnection = null;
try{
File file = new File("/Users/pathtofile/file.pdb");
URL url = new URL("http://example.website/api/jobs/5/");
urlconnection = url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
try {
((HttpURLConnection)urlconnection).setRequestMethod("PUT");
((HttpURLConnection)urlconnection).setRequestProperty("Content-Type",
"application/json");
((HttpURLConnection)urlconnection).connect();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
System.out.println("ProtocolException");
e.printStackTrace();
}
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection
.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) >= 0) {
bos.write(i);
}
bos.close();
// Getting error here (Bad request).
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
} catch(Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
try {
InputStream inputStream;
int responseCode = ((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode >= 200) && (responseCode <= 202)) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >= 0) {
System.out.println(j);
}
} else {
System.out.println(responseCode);
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
System.out.println(inputStream);
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException");
e.printStackTrace();
}
And I get the following error:
Bad Request
400
Is there a way to send a file using PUT method? The file is going to be in a place lıke this:
{"target":["This field is required."],
"project":["This field is required."],
"option":["This field is required."],
"result_file":["No file was submitted."],
"com_status":["This field is required."]}
The above is output from curl PUT method that I tried without giving any parameters. And it also shows that the parameters are required in a JSON format.
Related
I've been trying to download the csv from the UK government coronavirus API. you can download the file manually by using the URL: https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=overview&structure=%7B%22areaName%22:%22areaName%22,%22date%22:%22date%22,%22newCasesBySpecimenDate%22:%22newCasesBySpecimenDate%22,%22cumCasesBySpecimenDate%22:%22cumCasesBySpecimenDate%22%7D&format=csv
I've tried multiple methods of downloading files, such as JavaIO:
InputStream in = null;
try {
in = new URL("https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=overview&structure=%7B%22areaName%22:%22areaName%22,%22date%22:%22date%22,%22newCasesBySpecimenDate%22:%22newCasesBySpecimenDate%22,%22cumCasesBySpecimenDate%22:%22cumCasesBySpecimenDate%22%7D&format=csv").openStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
Files.copy(in, Paths.get("test.csv"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
and Java NIO:
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("test.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileChannel fileChannel = fileOutputStream.getChannel();
try {
fileOutputStream.getChannel()
.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
} catch (IOException e) {
e.printStackTrace();
}
however, it only shows this in the file:
‹ 0w®_ÿ}ZKŽX5Üs
àHm÷ÏÞ;$6ˆŒÈe‘€HâöTy²L=)Š”y»ÝŸru{^þ~}ùååãëxÿòåu|zý÷ǗϯŸøï׿^ÿðñõÓOüñïÿ|üÆ¿ûíÓ‡/¯ï¿ÿùç?Þÿùq,[önNü3,Ç\Çæ ³1ÛN·wï£pvÆjÛ\Ï:Kâö˜§66_ez=ì¸}½Vœµ%®Æò•°rY•™Ä%p½`–õÔ¸ ®xŽ™§VKœ•8ÏÒ¶†Ï¨nZ˜ö<’1¦ÁË^ßÆÙ;®bÃ;V>•Ÿ³±V]\T[*ÜBÜÜž¶Âæ–¸M¿,œ×Ìjk\8ë8݈„!lE÷\'µuI¯¸³*¦KÜV+±¼²M³Ýc#`Ka1¥¼ÆnØ6%l""|ì8=õˆô™c¯X-ã5óiïÑgŸl CA2x4¼RGÂ÷èêÑyæ–Q˜HK„ °ˆ˜z5Dar¤WõÔG–ö‰X[ÃP[{ƒQE©i"Õ¦UXTF4†Êߣ ¬OJ‚H¬Y¾gËMÁbÈ7d²©tö’ÄÎ;!mûÊas u¤{Q°ìÁL°
Q#Éì‘YXTÂœ«9JP–Œ]†Ë¹qú¤ˆ‚WŸ‘`—1%{ùìBç·7µCRBÓ`Žo'‘æ#šËÕ#I¼0À®-ˆ($Úe‘µED‰ªQ#ÊoJT¢à3Týt½* PZáHomjØòÑz°9¨æXÈò–(¤X¢¢EL¢9ÁµìÌ#½
"Š]ð½ùnix(Nùðõ…Íʉ‚Òž¸®B;hYQ9 TZʃ»5ãáŒ÷" ª·½#îjÜß ÑÔgœØ•î
µ¢w4X³ö*èçÞÅ^å-íû ëk6Ûµî¶!§|ŠèëZm=ÅËÖÓCç=M2çZöPC ‡†½3$
¾?Œ#Œ{#á
¦ös”H‰¼ßW2¥1L¸Í5
Ü4™Ñ¾MÈR HMk1LµÅmCÔ¦!*k¶DázÈ»£q…Û~
NJ…<ãß
‘ATÐzäÄ:ûa-§Vh—¹-€
îÖÞ‚ç'³~ÕI½<ôÃÊNéÓIÏb
7¹õ»è7Ó;ÎÛÎ Ÿ¬“^ʃZ£¼Î-Õ=¡Ù–‘¦2šè Øýèýx%³Ê -VHÔ¢à!
ÂMzž²È!) <wëµèù¾Jê<+ñ:Õg!ý R‚Nˆá‘ 'Xÿ³]‡r膙¬E5ÄëÓÑ›š6ýÔ$j£i’(g—7X׃ñkP/¹UêHƒfò®TR¸4 b Å“M>:,U‹=K®Rrž—§Dmô(p¨!çS‚Ð1aðO!ñ BIð6jG ‚\Üñi ¢HâJf
‡F:‡7*Aë+Â#o7G#§»Ò-A66/}ôKžŽú(¸RÍ)#|å:á“¥ø¥ÉBÙ4µ§W*ÈÄ (R$ÔMÑz»#…AsJ€ƒØn¯³TƒLÒ²x:t5ÚO‘ ùÃJ¤qqPŸ2vàŸžÜÎÜdf‚š34[Úþ)j†½¥0oòOS²eu‚~íÂÚ;K‚‚ú˜ ü#‚œ}#UKoÇV“Û•…t&NVµ(r$è·AEZ©É•Ð)4>;Ð÷KrŠ¢7Ô]·û‚#HŠªzk¾¾{A¬J{/úi–¢ßº¬ÒŒÒ†CßlºÀ¦’]uõ
ô'šc7éÌEãt½ãátðø†MJ%A`•ƒž}‘žävWÜ0.»GºœâÆ&MO‰âD’µÐhͤ«8ù1æ'aÚ®€¤æÑn˜ô:mÇå®Aœ/2_X1S¢&OˆµêÌÔ(
úƒŒ©=]ÚΉ4P…&U¢èù»V¶bŽ"½4çx¥jÙ$ôr)=몛É9dù,iª¶?«–…Œ!Õ“‰zJ£àù8Ø×̃·øhàì[ͽ,oÃe›sOÔ~Iãs‡¨PLE…“œg¸˜b…ø w jÉv$oõ9G¸\¢PÅë-ô˜$oÃU´ýéƒõqÇg#åy°ÞyF¢"}K‚cÌÔ ü’(:´‘_`¤ÔÖßjåSÇví¯+œyË¡-i=1É]èòT{—•¶ó±Æ|VZFMšW,Ÿd%zócšôÇ&|Áüíò·ñÍZ¦fýD-N°ÖìR•–w””X3Vh]ã&: ‰â{ÿÞèé%jßVÿF‡&ãx§SÌBCO¥QèÞØÒO¨íX…¾¥6gó™Sæ=•óí èÒ_v9gé;´ïù‚†•Ñ2sŒÓâ‹B¼EN9'NÝWT×zs ¡#b½Ò[¢6wäs\ËÛ8È9A9‰Xºª¡ ç8ñ™]J9Ç;85
YAÎAïaœy…ºÑ‚œ“¸<AçðªF¡ç
ˆ—Hm}_œ8ÄvíUø~ƒ¿&#¨ârΦ]¨ðEßóê^ W¹#ÇÏ'ö½¤^=-Ä>hÛd'ß6’ívÅ”ùÎáÓ å‰ë8pßð¥Ð"ícÇ8ýú„dðå>’ƃ„s‚óMFÚ8öO¹:µ#79‘Ñ]¥ã¶¹Ï¢=S»Óê><*Ó§#×#Ž õé-ê ܇h¢æѧƒÇûmŸÚO äzá/Ü4ßV‚HREï#¨!“Cmç—‹p óbQÛù}žgÑ,ùJ[5^ü%ËÏID(a
9ßñËCF•n{éíòês’èÃvÍç{s½’ó*ä0¶R:“¿s€ìæ kIg¾Mš7
Aüj1÷õÙÛ)À)3ú!´uj²á$ŸsÞ® apPz'4½ÕÒ‡“ï‘wâ(ÏÄ÷.ª„šÒdŠñ¥(ÐÉ5±o#5„/‚÷·…ô‰Ø‰€Aøm¶ç^òÈdÞ˜z‰ÅçPéöWdE½˜œ}¯<…„. Žlx£Ë!“ð7jdºÞ‡«¡Ûº
^ŸùkQCåÖº³\¤üŽÃþò34Ô·ne5ú\·™ª?Y¬fzF~žüßú³áK¯¡xŸ¾îǯýøµ¿æã×xüê_×ãW:K¥¯dYŠ_¡¯†L?£¯dX=~Ej=|¥¯dbš?~]_§þ:ya?}Å7|ý:7é…)
I then moved on to trying to make an http request, which I used this code:
URL url = new URL("https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=overview&structure=%7B%22areaName%22:%22areaName%22,%22date%22:%22date%22,%22newCasesBySpecimenDate%22:%22newCasesBySpecimenDate%22,%22cumCasesBySpecimenDate%22:%22cumCasesBySpecimenDate%22%7D&format=csv");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
which only returns
0w�_�}ZK�X5�s�Hm���;$6��e��H��Ty�L=)��y�ݟru{^�~}�����x���u|z��Ǘϯ���^�����O����|�Ə���Ӈ/����ç?���q,[�nN�3,�\�� �1�N�w�pv�j�\�:K����66_ez=�}�V��%���rY���%p�`��Ը �x���VK���8����ϨnZ��<�1���^���;�b�;V>�����V]\T[*�B�܁���斸M�,���jk\�8�8��!lE��\'�uI����*�K�V+���M���c#`Ka1���n�6%l""|�8=����c�X-�5�i��g�l CA2x4�RG�����y�Q�HK� ���z5Dar�W�����X[�P[{�Q�E�i"��UXTF�4��ߣ �OJ�H�Y�g�M�b�7d��t����;!m��asu�{�Q���L�Q#��YXT���9JP��]����q����W��`�1%{��B�7�CRB�`�o'���#����#I�0��-��($ځe��ED��Q�#�oJT��3T�t�*�PZ�Homj���z�9��X��(�X��EL�9����#�"�]��nix(N������ʉ�Ґ���B;hY�Q9 TZ���5���" ���#�j�� ��g������w4X����*����^�-�� �k6۵�!��|���Zm=����C�=M2�Z�PC ���3$�?�#�{#���s�H���W2�1L��5�4�ѾM�R�HMk1L��mCԦ!*k�D�zȻ�q��~NJ�<��AT�z��:�a-�Vh��-����ނ�'�~�I�<���N��I�b7����7�;��� ���^ʃZ����-�=�ٖ��2�� ����x%�ʠ-VHԢ�!�Mz���!) <w����J�<+�:Õg!� R�N�ᑠ'X��]�r����E5���ћ�6���$j�i�(g�7X׃�kP/�U�H�f�TR�4 b�œM>:,U�=K��Rr����Dm�(p�!�S��1a�O!� BI�6jG �\��i �H�Jf��F:�7*A��#o7G#���-A66/}�K���(�R�)#|�:ᓥ���B�4��W*�� (R$�MÑz�#�AsJ���n��T�LҲx:t5�O���� ��J��qqP�2v������df��34[��)j���0o�OS�eu�~��ڍ;K���� �#��}#UKo�V�ە�t&NV�(r$�AEZ�ɕ�)�4>;��Kr��7ԭ]���#H��zk���{A�J{/�i��ߺ�Ҍ��҆C�l����]u��'�c7��E��t���t���MJ%A`���}���vW�0.�G����&M��D���hͤ�8�1�'aڮ����n��:m��A�/2_X1S�&O�����(����=]�Ή4P�&U����V�b�"�4�x�j�$�r)=몛�9d�,i��?����!Ս��zJ���8��̃��h��[ͽ,o�e�sO�~I�s��PLE���g��b���w j�v$oõ9G�\�P��-��$o�U����q�g#�y��yF�"}K�c�Ԡ��(:��_`����j�S�v�+�yˡ�-i=1�]��T{������|VZFM�W,�d%z�c����&|�������Z�f�D-N���R��w��X3Vh]�&: ��{����%j�V�F�&�x�S�BCO�Q����O��X���6g�S�=���� ��_v9g�;�������2s���B�EN9'N�W�T�z�s �#b��[�6w�s\��8�9A9�X��� �8�]J9�;85YA�A�a�y��т���<A��F����Hm}_�8�v�U�~��&#���rΦ]��E���^�W�#��'����^=-�>h�d'�6��vŔ���� ��8p����"�c�8���d��>�ƃ�s���MF�8��:�#79��]����Ϣ=S���><�*ӧ#�#����-�� ܇h��ѧ���m��O �z�/�4�V�HRE�#�!�Cm痋p �bQ��}�g�,�J[5^�%��ID(a9���CF�n{����s���v��{s���*�0�R:��s���kIg�M�7A�j1����)�)3�!�uj��$�s a�pPz'4��҇��w�(���.����d��(��5�o#5�/�����؉�A�m��^��dޘz���P��WdE���}�<���. �lx��!��7jd�އ��ۺ^���kQC�ֺ�\�������34��ne5�\���?Y�fzF~������K��x���ǯ�������x��_��W:K��dY�_���L?��dX=~Ej=|��db�?~]�_��:ya?}�7|�:7��)
when outputting content.
Can anyone help me?
In violation of the HTTP protocol, the server returns the csv data with Content-Encoding: gzip, even if you explicitly send an Accept-Encoding: identity header. You will need to decompress the response body.
This constraint is actually documented in the Developers guide for this API:
All API responses are compressed using GZip. The request client must therefore accept GZip encoded content.
Something like this should work, and continue to work if the server starts sending uncompressed responses against our (now explicit) request:
URLConnection connection;
try {
connection = new URL("...").openConnection();
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
InputStream in = connection.getInputStream();
String encoding = connection.getContentEncoding();
if ("identity".equals(encoding)) {
// Nothing to do.
} else if ("gzip".equals(encoding)) {
in = new GZIPInputStream(in);
} else {
throw IOException("Unsupported encoding " + encoding);
}
try {
Files.copy(in, Paths.get("test.csv"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
Note that neither this code, nor your own, closes the connections and streams properly. I recommend to use try-with-resources to close things gracefully even in case of an exception.
You could save yourself some headaches by using a third-party HTTP library, such as OkHttp or Apache HttpClient.
I have a class audio sender which makes a connection to the nodejs server and uploads an audio file in POST method mode.
public class AudioSender implements Callable<JSONObject> {
String outputFile;
AudioSender(String fileLocation){
outputFile=fileLocation;
}
public JSONObject call(){
URL url = null;
HttpURLConnection urlConnection = null;
InputStream audioInputStream=null;
JSONObject response=null;
byte buffer[]=new byte[16];
try {
url = new URL("http://192.168.0.106:3000/upload");
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(16);
urlConnection.setRequestProperty("Content-Type","multipart/form-data");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=*****");
try {
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
try {
audioInputStream = new BufferedInputStream(new FileInputStream(outputFile));
Log.d("hello","audioinputstream");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
while(audioInputStream.read(buffer)!=-1) {
out.write(buffer);
Log.d("buffer",buffer.toString());
}
try {
audioInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder total = new StringBuilder();
while(in.read(buffer)!=-1)
total.append(buffer);
Log.d("response",total.toString());
try {
response = new JSONObject(total.toString());
}catch(JSONException e){
Log.e("Response Parse Error", "Could not parse malformed JSON");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
This is the upload that executes the AudioSender callable.
public void upload() {
JSONObject response=null;
AudioSender sender=new AudioSender(outputFile);
FutureTask<JSONObject> uploadTask=new FutureTask<JSONObject>(sender);
ExecutorService executorService= Executors.newFixedThreadPool(1);
executorService.execute(uploadTask);
Log.d("s","was here");
while(true){
if(uploadTask.isDone()){
try{
response=uploadTask.get();
}catch(InterruptedException|ExecutionException e){
e.printStackTrace();
Log.e("ee","ee",e.getCause());
}
}
}
}
I pretty much know this isn't node js's fault but here's the server code:
app.post('/upload',function(req,res){
console.log("someone called!");
req.on('data',function(chunk){
console.log('res');
console.log(chunk);
});
req.on('end',function(){
console.log("done!");
res.send({'name':'sg'});
});});
When I call upload(), the server console prints
someone called!
done!
I was debugging and found that indeed I am receiving the responded json object from the server. And I don't know if out.write(buffer) is doing the job, but debugging it shows that the buffer value is changing and is in par with my audio file's size.
Please do not suggest using ION or anything else.
I solved the problems by setting up the URLConnection as follows:
boundary = "===" + System.currentTimeMillis() + "===";
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // indicates POST method
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
I don't know why i get a null value when i call the GetPHPData() function. The "out" variable returns nothing (""). I make a Toast.makeTest and it returns empty string. Please help. This is my code:
public class PHPConnect extends Activity
{
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String out = null;
public String GetPHPData()
{
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
out = readStream(in);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally
{
urlConnection.disconnect();
return out;
}
}
private String readStream(BufferedReader is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e)
{
return e.getMessage();
}
}
}
By the way, im running a wamp server and I port forwarded my router, on local host, the url works, but on remote connection, it won't return a string. You can try out the url, the result is: "This is the output:emil"
Can you please try below piece of code which is working for me, also add INTERNET permission in android manifest file. Still if it is not working then may be issue with server end then try to debug it.
URL url;
try {
url = new URL("myurl");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Some PHP sites use a page to act as a middle man for handling file downloads.
With a browser this works transparently. There seems to a be a slight pause while the php page processes the request.
However, attempting a download through Java using a URL or HttpURLConnection returns a plain html page. How could I get the file downloads working in the same way?
Edit: Here is an example link:
http://depot.eice.be/index.php?annee_g=jour&cours=poo
Edit: Here is some of the code I've been testing:
// This returns an HTML page
private void downloadURL(String theURL) {
URL url;
InputStream is = null;
DataInputStream dis;
String s;
StringBuffer sb = new StringBuffer();
try {
url = new URL(theURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK)
return;
InputStream in = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int i;
while ((i = in.read()) != -1) {
bos.write(i);
}
byte[] b = bos.toByteArray();
FileOutputStream fos = new FileOutputStream( getNameFromUrl( theURL ) );
fos.write(b);
fos.close();
conn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// This will throw Exceptions if the URL isn't in the expected format
public String getNameFromUrl(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.');
System.out.println("url:" + url + "," + slashIndex + "," + dotIndex);
if (dotIndex == -1) {
return url.substring(slashIndex + 1);
} else {
try {
return url.substring(slashIndex + 1, url.length());
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
}
Considering no other constrains, you can read the redirected URL from the HTTP header and connect to that URL directly from JAVA.
There is an API setting to follow redirects automatically – but it should be true by default. How do you access the URL?
See Java API docs...
I think I've found a solution using HttpUnit. The source of the framework is available if you wish to see how this is handled.
public void downloadURL(String url) throws IOException {
WebConversation wc = new WebConversation();
WebResponse indexResp = wc.getResource(new GetMethodWebRequest(url));
WebLink[] links = new WebLink[1];
try {
links = indexResp.getLinks();
} catch (SAXException ex) {
// Log
}
for (WebLink link : links) {
try {
link.click();
} catch (SAXException ex) {
// Log
}
WebResponse resp = wc.getCurrentPage();
String fileName = resp.getURL().getFile();
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
System.out.println("filename:" + fileName);
File file = new File(fileName);
BufferedInputStream bis = new BufferedInputStream(
resp.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bis.close();
bos.close();
}
System.out.println("Done downloading.");
}
I am writing a desktop app in Java to upload a file to a folder on IIS server using HTTP PUT.
URLConnection urlconnection=null;
try{
File file = new File("C:/test.txt");
URL url = new URL("http://192.168.5.27/Test/test.txt");
urlconnection = url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
try {
((HttpURLConnection)urlconnection).setRequestMethod("PUT");
((HttpURLConnection)urlconnection).setRequestProperty("Content-type", "text/html");
((HttpURLConnection)urlconnection).connect();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection
.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) >0) {
bos.write(i);
}
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try {
InputStream inputStream;
int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode>= 200) &&(responseCode<=202) ) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >0) {
System.out.println(j);
}
} else {
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This program creates an empty file on the destination folder (Test). The contents are not written to the file.
What is wrong with this program?
After you complete the loop where you are writing the BufferedOutputStream, call bos.close(). That flushes the buffered data before closing the stream.
Possible bug: bis.read() can return a valid 0. You'll need to change the while condition to >= 0.