how to insert %20 in place of space in android

旧街凉风 提交于 2019-12-17 18:33:08

问题


I have a xml URL file in which there are white spaces i want to replace white spaces with %20.. how to do this????

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();

/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
                "http://www.arteonline.mobi/iphone/output.php?gallery=MALBA%20-%20MUSEO%20DE%20ARTE%20LATINOAMERICANO%20DE%20BUENOS%20AIRES");

XMLHandlerartistspace myXMLHandler = new XMLHandlerartistspace();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));

回答1:


Try this:

String temp = http://www.arteonline.mobi/iphone/output.php?gallery=MALBA%20-%20MUSEO%20DE%20ARTE%20LATINOAMERICANO%20DE%20BUENOS%20AIRES

temp = temp.replaceAll(" ", "%20");
URL sourceUrl = new URL(temp);



回答2:


When you build your URL you should use URLEncoder to encode the parameters.

StringBuilder query = new StringBuilder();
query.append("gallery=");
query.append(URLEncoder.encode(value, "UTF-8"));

If you already have the whole URL in a String or a java.net.URL, you could grab the query part and rebuild while URLEncoding each parameter value.




回答3:


just one addition to sudocode's response:

use android.net.Uri.encode instead of URLEncoder.encode to avoid the "spaces getting converted into +" problem. Then you get rid of the String.replaceAll() and its more elegant :)

StringBuilder query = new StringBuilder();
query.append("gallery=");
query.append(android.net.Uri.encode(value, "UTF-8"));



回答4:


I guess you want to replace all spaces, not only white.

the simplest way is to use

"url_with_spaces".replaceAll(" ", "%20);

However you should consider also other characters in the url. See Recommended method for escaping HTML in Java




回答5:


String s = "my string";
s=s.replaceAll(" ", "%20");



回答6:


Try using URIUtil.encodePath method from the api org.apache.commons.httpclient.util.URIUtil.

This should do the trick for you.




回答7:


For anyone that needs space characters to be encoded as a %20 value instead of a + value, use:

String encodedString = URLEncoder.encode(originalString,"UTF-8").replaceAll("\\+", "%20")


来源:https://stackoverflow.com/questions/6045377/how-to-insert-20-in-place-of-space-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!