URL获取参数的问题

时间:2014-03-31 15:14:14

标签: java android

我正在编写一个可以从Internet获取内容的Android应用程序。 URL由一些带有String值的查询参数组成。问题是,当我尝试使用包含一些空间的字符串值时,它不起作用。但是,其他人工作正常。这是我用来获取get方法内容的代码。

URL url = new URL("http://www.example.com/fetch.php?title="+someStringValue);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
while((temp=br.readLine())!=null){
    data+=temp;
}

问题是我不能为变量someStringValue使用间隔字符串。我知道有一些编码问题,但我该如何解决呢? 此外,使用GET方法从URL读取数据数据的最佳方式是什么?

3 个答案:

答案 0 :(得分:3)

修改:

fge 实际上是正确的,URLEncoder会为空格提供“+”而不是“%20”。

因为你在Android上我推荐简单的替代方案:

URL url = new URL("http://www.example.comfetch.php?title=" +
    Uri.encode(someStringValue));

使用Uri.encode

答案 1 :(得分:3)

好吧,所以,在一个常见的误解之前就会出现......

URLEncoder不起作用。

URLEncoderapplication/x-www-form-urlencoded数据的数据进行编码。这不是用于转义URI查询片段的内容。首先,转义字符集是不同的;当然,这个方法存在的问题是用+编码空格。

以下是三种解决方案......


使用URI构造函数:

// Put title string UNESCAPED; the constructor will escape for you
final URL url = new URI("http", null, "www.example.com", -1, "/fecth.php",
    "title=yourtitle", null).toURL();

如果您使用的是番石榴(15岁以上),那么您可以使用this class,这也可以完成工作:

final Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
final String escapedTitle = escaper.escape("yourtitlestring");

final URL url = new URL("http://www.example.com/fetch.php?title="
    + escapedTitle);

bazooka杀死苍蝇:URI模板。 Using this library

final URITemplate template 
    = new URITemplate("http://www.example.com/fetch.php?title={title}");

final VariableMap varmap = VariableMap.newBuilder()
    .addScalar("title", "yourtitlehere")
    .build();

final URL url = template.toURL(varmap);

答案 2 :(得分:1)

您需要使用代码“%20”替换空格。 URL编码用此代码替换空格。

要读取数据,我通常使用BufferedReader,但是这样:

URL url = new URL("URL");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s, response = "";
while ((s = rd.readLine()) != null) {
    response += s;
}