如何在安卓中插入%20代替空格

2022-09-01 06:19:19

我有一个xml URL文件,其中有空格,我想用%20替换空格。如何做到这一点????

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

试试这个:

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

构建 URL 时,应使用 URLEncoder 对参数进行编码。

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

如果您已经在字符串或java.net.URL中拥有整个URL,则可以在URL编码每个参数值时获取查询部分并重新构建。