I need to open a filename using a URL(java.net.URL) as below:
file:/C:/RAdev/Basic/src/test/resources/xml Data/test
dir/app-config-seed-data.xml
I've the following java code to read
fileURL = new File(filePath).toURI().toURL();
is = fileURL.openStream();
Since windows can access file:\, even URL should be able to open the same.
Workaround used for now:
public static final String FILE_URL_PREFIX = "file:";
if (filePath.contains(FILE_URL_PREFIX)) {
filePath = filePath.replaceAll("file:/", "");
System.out.println("Modified filepath - " + filePath);
}
fileURL = new File(filePath).toURI().toURL();
is = fileURL.openStream();
Is the above workaround needed, please let me know if there is another way to reap the benefits of URL accessing. I'm new to URL/URI in java, help is really appreciated.
Thanks.
file:/C:/ is not a valid file url. Try starting your URLs with file://C:/.
Additionally, the File(String) constructor does not take a URL, it takes a local file path. If you have a URL as a string that you want to parse, use the URL(String) constructor:
URL fileURL = new URL("file://C:/RAdev/Basic/src/test/resources/xml Data/test dir/app-config-seed-data.xml");
is = fileURL.openStream();
Adding the below implementation on top of Darth Android suggestion worked:
URL url = new URL(filePath);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),
url.getPort(), url.getPath(), url.getQuery(),
url.getRef());
URL fileURL = uri.toURL();
InputStream is = fileURL.openStream();
Related
I can not find an answer to that and I do not know how to compile org.apache.commons.lang.StringEscapeUtils, which is the only solution I found on the internet.
Also, I do not understand why I can not do something like this
s = s.replaceAll(" ","\\ ");
I think you can use
URLEncoder.encode("your URL here", "UTF8")
Use this:
String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
Source: Url encoding in Android
This should be the correct answer in that post.
Currently there is final URL url = new URL(urlString); but I run into server not supporting non-ASCII in path.
Using Java (Android) I need to encode URL from
http://acmeserver.com/download/agc/fcms/儿子去哪儿/儿子去哪儿.png
to
http://acmeserver.com/download/agc/fcms/%E5%84%BF%E5%AD%90%E5%8E%BB%E5%93%AA%E5%84%BF/%E5%84%BF%E5%AD%90%E5%8E%BB%E5%93%AA%E5%84%BF.png
just like browsers do.
I checked URLEncoder.encode(s, "UTF-8"); but it also encodes / slashes
http%3A%2F%2acmeserver.com%2Fdownload%2Fagc%2Ffcms%2F%E5%84%BF%E5%AD%90%E5%8E%BB%E5%93%AA%E5%84%BF%2F%E5%84%BF%E5%AD%90%E5%8E%BB%E5%93%AA%E5%84%BF.png
Is there way to do it simply without parsing string that the method gets?
from http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
B.2.1 Non-ASCII characters in URI attribute values Although URIs do
not contain non-ASCII values (see [URI], section 2.1) authors
sometimes specify them in attribute values expecting URIs (i.e.,
defined with %URI; in the DTD). For instance, the following href value
is illegal:
...
We recommend that user agents adopt the following convention for
handling non-ASCII characters in such cases:
Represent each character in UTF-8 (see [RFC2279]) as one or more
bytes.
Escape these bytes with the URI escaping mechanism (i.e., by
converting each byte to %HH, where HH is the hexadecimal notation of
the byte value).
You should just encode the special characters and the parse them together. If you tried to encode the entire URI then you'd run into problems.
Stick with:
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
Check out this great guide on URL encoding.
That being said, a little bit of searching suggests that there may be other ways to do what you want:
Give this a try:
String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
(You will need to have those spaces encoded so you can use it for a request.)
This takes advantage of a couple features available to you in Android
classes. First, the URL class can break a url into its proper
components so there is no need for you to do any string search/replace
work. Secondly, this approach takes advantage of the URI class
feature of properly escaping components when you construct a URI via
components rather than from a single string.
The beauty of this approach is that you can take any valid url string
and have it work without needing any special knowledge of it yourself.
final URL url = new URL( new URI(urlString).toASCIIString() );
worked for me.
I did it as below, which is cumbersome
//was: final URL url = new URL(urlString);
String asciiString;
try {
asciiString = new URL(urlString).toURI().toASCIIString();
} catch (URISyntaxException e1) {
Log.e(TAG, "Error new URL(urlString).toURI().toASCIIString() " + urlString + " : " + e1);
return null;
}
Log.v(TAG, urlString+" -> "+ asciiString );
final URL url = new URL(asciiString);
url is later used in
connection = (HttpURLConnection) url.openConnection();
So I have an ArrayList of String objects that I want to send in a Http POST request using the Apache Http Client.
What I am doing now is concatenating the List objects to a new String each followed by a System.getProperty("line.separator") for a linebreak.
However I get a bad response from the server, telling my the URL is malformed.
Thanks in advance for your help!
ArrayList<String> episodeList
String episodesAsString = "";
for(String s : episodeList)
episodesAsString = episodesAsString.concat(s + NL);
URI uri = new URI(
"https",
"my.domain.com",
"/path/add?this=123456&application=myApp&event=myEvent&description=" + episodesAsString,
null);
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(uri);
HttpResponse response = client.execute(request);
It seems by NL you mean new line character. Instead after concatinating all the strings and using \n instead of NL, use URLEncoder to encode the string. Also check if the URL is being passed badly in debug.
In your case you are not sending POST data. The problem might be with bad URL.
Try this:
String strUrl = "http://localhost:7001/RESTFUL_Tutorial/rest/hello/test1/test naveen kumar/test pwd";
URL url = new URL(strUrl);
// for getting URI
URI urlinfo = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
// for getting URL
url = urlinfo.toURL();
For more better use URLEncoder
place your url.. :)
I think the URI is the problem. Even though I think you can construct a proper URL using it, you are missing the '//' before the hostname. I your example, I believe the request would be going to:
https:my.domain.com/path/addthis=123456&application=myApp&event=myEvent&description=XXX
This is based on the 5min I just spent reading the JavaDoc of the URI class. You could probably test this by putting a Proxy or sniffer on and seeing what the payload of the headers look like.
In my app, there is an ImageView that display an image from a URL.
I download the image using this method:
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
This works only with URLs that has numbers or english letters and doesn't work with any other chars (like spaces):
Good URL: http://site.com/images/image.png
Bad URL: http://site.com/images/image 1.png
I tried to chage the URL encoding (URLEncoder.encode), but it changes the whole URL (incliding slashes, ect...).
Do I need to replace some chars after the encoding? or maybe there is a better way?
Thanks :)
"Url encoding in Android"
You don't encode the entire URL, only parts of it that come from
"unreliable sources". -yanchenko
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "https://stackoverflow.com/search?q=" + query;
This is fine if you are just dealing with a specific part of a URL and
you know how to construct or reconstruct the URL. For a more general
approach which can handle any url string, see my answer below. – Craig
B
String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
below is my code
DocsService client = new DocsService("testappv1");
client.setUserCredentials(username, password);
client.setProtocolVersion(DocsService.Versions.V2);
File file = new File("C:/test.jpg");
DocumentEntry newDocument = new DocumentEntry();
newDocument.setTitle(new PlainTextConstruct("test"));
String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
newDocument.setMediaSource(new MediaFileSource(file, mimeType));
newDocument = client.insert(destFolderUrl, newDocument);
the document was created successful, but it did not contain anything.
try the following
client.insert(new URL("https://docs.google.com/feeds/documents/private/full/?convert=false"), newDocument);
i think the ?convert=false bit is important, not sure how you do that without the url
client.insert(new URL(destFolderUrl+ "?convert=false"), newDocument);
would hopefully work in your case