Java InputStream NullPointerException with InputStream - java

I've got two methods in a class:
private static InputStream getSongStream(String ip, String id){
try {
URL url = new URL("http://"+ ip + "/" + Client.streamphp);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data); //Data is a simple Http Post that is know to work
wr.flush();
wr.close();
return conn.getInputStream();
} catch (MalformedURLException badurl) {
System.out.println(badurl);
return null;
} catch (IOException noconnection) {
System.out.println(noconnection);
return null;
}
}
public static void downloadSong(String ip, String id, String path){
InputStream rd = Client.getSongStream(ip, id);
try {
OutputStream stream = new FileOutputStream(new File(path));
byte[] buffer = new byte[4096];
int len;
while ((len = rd.read(buffer)) > 0) { //Here I get NullPointerException
stream.write(buffer, 0, len);
}
stream.close();
rd.close();
} catch (IOException noconnection) {
System.out.println(noconnection);
}
}
The line commented in the second method is the problem, if I put all in the same method I can download the song without problems, but not if I separate them.
Any ideas? I would like to have them separated to reuse getSongStream.

The problem is that you're swallowing exceptions in getSongStream and returning null. Don't do that - let the exception propagate up, possibly having wrapped it in another form... so declare that your method can throw (say) IOException. Your downloadSong method should probably declare that it can throw IOException too. Note that you should have finally blocks to make sure you close your streams appropriately even if an exception is thrown.
It's almost always a bad idea to catch an exception, write it out to standard output and then proceed as if everything is okay.

Related

How to download csv from uk government coronavirus api

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.

Convert outputstream byte array into string

I am trying to send a file path to a Rest Api through DataOutputStream. DataOutputStream converts string into bytes and I am having trouble converting the byte back to desired String.
Here is my method that calls Api
private void sendFilePath(String filePath) {
try {
URL url = new URL("http://localhost:8080/uploadExcelFile");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-
form-urlencoded");
connection.setDoOutput(true);
connection.setDoInput(true);
DataOutputStream outputStream = new
DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(filePath);
outputStream.flush();
outputStream.close();
connection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
}
and here is controller method aka Api
#PostMapping("/uploadExcelFile")
public HttpStatus uploadFile(#RequestBody byte[] byteFilePath) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(byteFilePath);
String filePath = baos.toString();
Workbook workbook = WorkbookFactory.create(new File(filePath));
List<StudentModel> students = studentService.convertExcelToData(workbook);
return studentHandler.createStudent(students);
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
return HttpStatus.BAD_REQUEST;
}
}
The filepath argument in sendFilePath() is D:\Projects\AutoFeeChallan\Aptech Student Records.xlsx
while the one I get in uploadApi after converting to String is D%3A%5CProjects%5CAutoFeeChallan%5CAptech+Student+Records.xlsx=
I want the same path in controller method as I send as argument in sendFilePath().
Can you suggest any solution or other methods to solve this problem.
By setting ,
connection.setRequestProperty("Content-Type", "application/x-www-
form-urlencoded");
you made the data URL encoded.At some point you need to urldecode it.
String filePath = java.net.URLDecoder.decode(baos.toString(), StandardCharsets.UTF_8);
Or you can change the content-type to different one.

NULL JSON Model passed to webservice when specific number of special characters

This is driving me mad - I have an object model in android that is turned into a JSON string using GsonBuilder:
WorkItemModel model = new WorkItemModel();
model.Jobs = jobList;
model.Items = itemList;
model.Images = imageList;
model.Questions = questionList;
String gsonJson = new GsonBuilder().create().toJson(model);
The string is passed to a c# webservice using this method :
private String callWebService(String JSONModel, URL url, int appId) throws Exception {
int connTimeout = 5000;
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
//Populate Header
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setChunkedStreamingMode(0);
conn.setConnectTimeout(connTimeout);
conn.setReadTimeout(connTimeout);
if (JSONModel != null) {
conn.setRequestProperty("Content-Length", String.valueOf(JSONModel.length()));
conn.setDoInput(true);
OutputStream stream = new BufferedOutputStream(conn.getOutputStream());
stream.write(JSONModel.getBytes());
stream.flush();
stream.close();
} else {
conn.setDoOutput(true);
conn.setChunkedStreamingMode(0);
conn.setRequestProperty("Content-Length", "0");
}
conn.connect();
BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder returnStringBuilder = new StringBuilder();
String streamString;
while ((streamString = inputStreamReader.readLine()) != null) {
returnStringBuilder.append(streamString);
}
inputStreamReader.close();
return returnStringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
throw e;
} catch (SocketTimeoutException e) {
throw e;
} catch (SSLHandshakeException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
} finally {
conn.disconnect();
}
return null;
}
The webservice should receive this model and then go away and do some back-end DB stuff - and for the most part, we don't have a problem, but we've had a few bug reports which I can replicate but can't seem to fix.
In the "Jobs" list in our model, we have a string property called completeNotes. When completeNotes is filled in with 4 "£" symbols, everything still works, but when there are 5 "£" symbols, the webservice Model it receives is NULL and I can see an exception has been thrown on the webservice :
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Additional information: Invalid character after parsing property name. Expected ':' but got: . Path 'Jobs', line 1, position 1585.
Just as a side note, this also happens with € symbols, except it only allows 2 € symbols.. on the third one it does the same thing - passes a NULL model through - the symbols don't have to be contiguous either
I won't show the whole JSON as its quite lengthy.. but the property I speak of is set like this in it :
"completeNotes":"£££££"
Has anyone got any ideas as to why this is happening - I've tried messing around with the encoding (setting it to UTF-8) but this doesn't seem to make a difference.
Have you tried adding "Charset=UTF-8' to the content type header?
conn.setRequestProperty("Content-Type", "application/json; Charset=UTF-8");

Java, FileNotfound Exception, While reading conn.getInputStream()

Please tell me some one, How to resolve this problem,
Sometime I am getting Filenotfound Exception and Some time this code working fine.
Below is my code,
public String sendSMS(String data, String url1) {
URL url;
String status = "Somthing wrong ";
try {
url = new URL(url1);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
wr.close();
} catch (MalformedURLException e) {
status = "MalformedURLException Exception in sendSMS";
e.printStackTrace();
} catch (IOException e) {
status = "IO Exception in sendSMS";
e.printStackTrace();
}
return status;
}
Rewrite like this and let me know how you go... (note closing of reading and writing streams, also the cleanup of streams if an exception is thrown).
public String sendSMS(String data, String url1) {
URL url;
OutputStreamWriter wr = null;
BufferedReader rd = null;
String status = "Somthing wrong ";
try {
url = new URL(url1);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (Exception e) {
if (wr != null) try { wr.close(); } catch (Exception x) {/*cleanup*/}
if (rd != null) try { rd.close(); } catch (Exception x) {/*cleanup*/}
e.printStackTrace();
}
return status;
}
This issue seems to be known, but for different reasons so its not clear why this happend.
Some threads would recommend closing the OutputStreamWriter as flushing it is not enough, therefor i would try to clos it directly after fushing as you are not using it in the code between the flush and close.
Other threads show that using a different connections like HttpURLConnection are avoiding this problem from occuring (Take a look here)
Another article suggests to use the URLEncoder class’ static method encode. This method takes a string and encodes it to a string that is ok to put in a URL.
Some similar questions:
URL is accessable with browser but still FileNotFoundException with URLConnection
URLConnection FileNotFoundException for non-standard HTTP port sources
URLConnection throwing FileNotFoundException
Wish you good luck.
It returns FileNotFoundException when the server response to HTTP request is code 404.
Check your URL.

java.io.FileNotFoundException when retrieving a url with umlauts in the filename

I am trying to retrieve a url with an umlaut in the filename, something like "http://somesimpledomain.com/some/path/überfile.txt", but it gives me a java.io.FileNotFoundException. I suspect that the filename on the remote server is encoded in latin1, though my url is in utf8. But my tries to change the encoding of the url weren't successful and I don't know how to debug it further. Please help!
Code is as follows:
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(uri).openConnection();
conn.setRequestMethod("GET");
} catch (MalformedURLException ex) {}
} catch (IOException ex){}
// Filter headers
int i=1;
String hKey;
while ((hKey = conn.getHeaderFieldKey(i)) != null) {
conn.getHeaderField(i);
i++;
}
// Open the file and output streams
InputStream in = null;
OutputStream out = null;
try {
in = conn.getInputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
out = response.getOutputStream();
} catch (IOException ex) {
}
Regards,
Hendrik
URL needs to be properly encoded. You have to know what charset/encoding your server is expecting. You can try this first,
String uri = "http://somesimpledomain.com/some/path/" +
URLEncoder.encode(filename, "ISO-8859-1");
If that doesn't work, replace "ISO-8859-1" with "UTF-8" and try again.
If that doesn't work either, file doesn't exist :)
Have you tried urlencoding it? E.g.
%FCberfile

Categories