2

我正在构建一个 URL 以使用 google-javi-api 访问用户 Google 日历,如下所示:

CalendarUrl url = CalendarUrl.forEventFeed("accountName", "private", "full");

它返回我这个网址:

"https://www.google.com/calendar/feeds/user@gmail.com/private/full?prettyprint=true"

我想用 startMin 和 startMax 参数设置这个 URL 的参数,所以 URL 最终看起来像这样:

"https://www.google.com/calendar/feeds/default/private/full?start-min=2011-06-00T00:00:00&start-max=2011-06-24T23:59:59"

我在这方面的所有尝试都失败了,在记录返回的 URL 后,我发现“?” 正在被“%3F”替换,和号被替换为“&”

返回的不正确的 url 是:

"https://www.google.com/calendar/feeds/default/private/full%3Fstart-min=2011-06-00T00:00:00&start-max=2011-06-24T23:59:59"

我很确定我的结果集为空的原因是因为这些字符替换。如何使用新参数附加原始 URL?

**如果您想知道我是如何构建这个 url 的,我正在使用Google Calendar的这个示例 Android 实现中的CalendarURL类。

编辑

更具体地说,在CalendarURL类中,我可以将部分添加到 URL 的“路径”,但我找不到包含查询参数的方法。此 API 是否不包含指定参数的方法?

4

2 回答 2

4

使用 google-java-client-api 创建 URL 的正确方法是扩展 GoogleUrl 对象。(我在这里使用 Google Latitude 作为示例。我创建了一个 GoogleUrl 对象,稍后您将看到它是如何使用的)。

Google URL 对象

  • 您构建一个扩展 GoogleUrl 的 URL 对象
  • 使用 @Key 注释在 URL 上注释要自定义的参数
  • 您提供了一个采用根 url 的构造函数。
  • 使用 pathParts.add 方法将部件添加到上下文中

示例 URL 对象如下所示:

public final class LatitudeUrl extends GoogleUrl {

  @Key
  public String granularity;

  @Key("min-time")
  public String minTime;

  @Key("max-time")
  public String maxTime;

  @Key("max-results")
  public String maxResults;

  /** Constructs a new Latitude URL from the given encoded URI. */
  public LatitudeUrl(String encodedUrl) {
    super(encodedUrl);
  }

  private static LatitudeUrl root() {
    return new LatitudeUrl("https://www.googleapis.com/latitude/v1");
  }

  public static LatitudeUrl forCurrentLocation() {
    LatitudeUrl result = root();
    result.pathParts.add("currentLocation");
    return result;
  }

  public static LatitudeUrl forLocation() {
    LatitudeUrl result = root();
    result.pathParts.add("location");
    return result;
  }

  public static LatitudeUrl forLocation(Long timestampMs) {
    LatitudeUrl result = forLocation();
    result.pathParts.add(timestampMs.toString());
    return result;
  }
}

用法

您使用此对象来构造 URL,只需填写您的参数(@Key 注释字段),然后执行 build() 方法以获取它的字符串表示形式:

    LatitudeUrl latitudeUrl = LatitudeUrl.forLocation();
    latitudeUrl.maxResults="20";
    latitudeUrl.minTime="123";
    latitudeUrl.minTime="456";

    System.out.println(latitudeUrl.build());

输出 :

https://www.googleapis.com/latitude/v1/location?max-results=20&min-time=456
于 2011-06-12T22:58:40.997 回答
1

经过一番认真的挖掘,我发现了如何使用 google-java-api 包含查询参数。

要将这些查询参数中的任何一个添加到 URL,请执行以下操作:

构建基本 CalendarUrl 后,调用 .put("Key", "Value") 添加查询参数。例如:

CalendarUrl eventFeedUrl = CalendarUrl.forEventFeed("user@gmail.com", "private", "full");

  eventFeedUrl.put("start-min", "2011-06-01T00:00:00");
  eventFeedUrl.put("start-max", "2011-06-22T00:00:00");

我只是碰巧在谷歌的项目主页中偶然发现了一个隐藏在一堆未经过滤的“问题”中的线程。有很多关于使用 gData api 的文档,但是没有关于 google-java-api 的文档。我花了将近 2 天的时间才找到这个简单的方法调用。非常令人沮丧。我希望读到这篇文章的人没有通过我所经历的来了解如何完成这个简单但至关重要的任务。它应该有更好的记录。

于 2011-06-12T18:32:17.353 回答