Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I was attempting to use this String as URL:

http://site-test.com/Meetings/IC/DownloadDocument?meetingId=c21c905c-8359-4bd6-b864-844709e05754&itemId=a4b724d1-282e-4b36-9d16-d619a807ba67&file=\\s604132shvw140\Test-Documents\c21c905c-8359-4bd6-b864-844709e05754_attachments\7e89c3cb-ce53-4a04-a9ee-1a584e157987\myDoc.pdf

In this code:

String fileToDownloadLocation = //The above string

URL fileToDownload = new URL(fileToDownloadLocation);

HttpGet httpget = new HttpGet(fileToDownload.toURI());

But at this point I am getting the error:

java.net.URISyntaxException: Illegal character in query at index 169:Blahblahblah

Then I have made some changes to the code like this:
 

String fileToDownloadLocation = //The above string

fileToDownloadLocation = URLEncoder.encode(fileToDownloadLocation, "UTF-8");

URL fileToDownload = new URL(fileToDownloadLocation);

HttpGet httpget = new HttpGet(fileToDownload.toURI());

However, when I try and run this code I get an error when I try to create the URL, the error then reads:

java.net.MalformedURLException: no protocol: http%3A%2F%2Fsite-test.testsite.com%2FMeetings%2FIC%2FDownloadDocument%3FmeetingId%3Dc21c905c-8359-4bd6-b864-844709e05754%26itemId%3Da4b724d1-282e-4b36-9d16-d619a807ba67%26file%3D%5C%5Cs604132shvw140%5CTest-Documents%5Cc21c905c-8359-4bd6-b864-844709e05754_attachments%5C7e89c3cb-ce53-4a04-a9ee-1a584e157987%myDoc.pdf

Any suggestions is greatly appreciated.

1 Answer

0 votes
by (13.1k points)

You need to encode your parameter’s value before concatenating them to URL.

Backslash character has to be escaped as %5C like this:

String paramValue = "param\\with\\backslash";

String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");

java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is a properly formatted URL string.

Want to learn Java? Check out the core Java certification from Intellipaat.

Related questions

Browse Categories

...