首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

精通 Grails 创建自定义插件(2)

精通 Grails 创建自定义插件(2)

创建 IsGd 类这个 Is.Gd(读作 is good)服务号称能够提供比 TinyUrl.com 更短的域名和编码 URL。访问 http://is.gd 试验这个 Web 界面。
为了再次表示我这种长短反差的偏好,我将借此机会向您展示我在 TinyUrl.groovy 中使用过的那个两行方法(参见 )的更长实现。如果服务失败,这个实现将提供更多信息以便做出相应反应。在 src/groovy/org/grails/shortenurl 中创建 IsGd.groovy,如清单 6 所示。
清单 6. IsGd 实用程序类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package org.grails.shortenurl

class IsGd{
  static String shorten(String longUrl){
    def addr = "http://is.gd/api.php?longurl=${longUrl}"
    def url = addr.toURL()
    def urlConnection = url.openConnection()
    if(urlConnection.responseCode == 200){
      return urlConnection.content.text
    }else{
      return "An error occurred: ${addr}\n" +
      "${urlConnection.responseCode} : ${urlConnection.responseMessage}"
    }
  }
}




如您所见,清单 6 的响应代码为 200 —— 表示 OK 的 HTTP 响应代码(参见  了解关于 HTTP 响应代码的更多信息)。为简便起见,调用失败时仅返回错误消息。但使用现成的扩展结构,您可以多次重新尝试调用或将故障转移到另一个 URL 缩短服务,从而使这个方法更健壮。
在 test/integration/org/grails/shortenurl 目录中创建对应的 IsGdTests.groovy 文件,如清单 7 所示。输入 grails test-app 并确认 IsGd 类工作正常。
清单 7. 测试 IsGd 类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package org.grails.shortenurl

class IsGdTests extends GroovyTestCase{
  def transactional = false
   
  void testShorten(){
    def shortUrl = IsGd.shorten("http://grails.org")
    assertEquals "http://is.gd/2oCZR", shortUrl        
  }
   
  void testBadUrl(){
    def shortUrl = IsGd.shorten("IAmNotAValidUrl")
    println shortUrl
    assertTrue shortUrl.startsWith("An error occurred:")
  }
}




传递 IAmNotAValidUrl 时,IsGd 服务将失败。要了解该服务是如何失败的详细信息,建议您跳到命令行并使用 curl 命令,如清单 8 所示。(cURL 实用程序是 UNIX®/Linux®/Mac OS X 上的原生命令,可以下载 Windows® 版本,参见 )。在浏览器中测试错误的 URL 可以看到错误消息,但看不到错误代码。使用 cURL,您可以清楚地看到,Web 服务返回一个 500 代码,而不是预期的 200。
清单 8. 使用 curl 查看失败 Web 服务类的细节
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ curl --verbose "http://is.gd/api.php?longurl=IAmNotAValidUrl"
* About to connect() to is.gd port 80 (#0)
*   Trying 78.31.109.147... connected
* Connected to is.gd (78.31.109.147) port 80 (#0)
> GET /api.php?longurl=IAmNotAValidUrl HTTP/1.1
> User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3
                 OpenSSL/0.9.7l zlib/1.2.3
> Host: is.gd
> Accept: */*
>
< HTTP/1.1 500 Internal Server Error
< X-Powered-By: PHP/5.2.6
< Content-type: text/html; charset=UTF-8
< Transfer-Encoding: chunked
< Date: Wed, 19 Aug 2009 17:33:04 GMT
< Server: lighttpd/1.4.22
<
* Connection #0 to host is.gd left intact
* Closing connection #0
Error: The URL entered was not valid.




现在这个插件的核心功能已经实现并经过测试,您应该创建一个方便的服务,以一种 Grails 友好的方式公开这两个实用程序类。
返回列表