Groovy 操作http请求


原文链接

http://blog.csdn.net/berdy/article/details/7726936

话不多说,先上一段代码,如果你使用过jquery,看到这样的代码是不是很亲切呢?

  1. def http = new HTTPBuilder('http://www.baidu.com')  
    http.request(GET,TEXT) {  
        //设置url相关信息  
        uri.path='/'  
        uri.query=[a:'1',b:2]  
        //设置请求头信息  
        headers.'User-Agent' = 'Mozill/5.0'  
        //设置成功响应的处理闭包  
        response.success= {resp,reader->  
            println resp.status  
            println resp.statusLine.statusCode  
            println resp.headers.'content-length'  
            System.out << reader  
        }  
        //根据响应状态码分别指定处理闭包  
        response.'404' = { println 'not found' }  
        //未根据响应码指定的失败处理闭包  
        response.failure = { println "Unexpected failure: ${resp.statusLine}" }  
    }  
    

      

request 方法中有三个参数1、请求方法 2、contenttype 3、 封装请求配置的一个闭包
在请求配置闭包中可以设置请求的相关参数以及对响应的处理闭包,更多详细配置可以参考:
http://groovy.codehaus.org/modules/http-builder/apidocs/groovyx/net/http/HTTPBuilder.RequestConfigDelegate.html

如果在request方法的参数中未设置ContentType参数,默认是使用ContentType.ANY,也就是说具体的文档类型取决于服务器端
指定了这参数后,就会强制按照这个参数来解析响应内容,而不管respone中的Content-Type值,几种常用的类型处理:
TEXT,纯文本
XML,采用XmlSlurper解析内容
HTML,先采用NekoHTML使HTML规范化,之后采用XmlSlurper解析DOM
JSON,采用JSON-lib解析内容

有了上面的粗略了解后,下面再各个细分详解:

1、GET请求


def http = new HTTPBuilder('http://www.google.com.hk')  
http.request(GET, TEXT) {  
    uri.path="/search"  
    uri.query = [q:'groovy']  
  
  
    response.success ={resp,reader->  
        println resp.statusLine.statusCode  
        println resp.headers.'content-length'  
        System.out << reader  
    }  
    response.failure={resp-> println resp.status }  
}  

  


上面的代码发起一个get请求,并对返回的html内容强制以TEXT形式处理
HTTPBuilder提供了一个更简洁的方式发送get请求

def http = new HTTPBuilder('http://www.google.com.hk')  
//简化的get请求  
def html = http.get(path:'/search',query:[q:'groovy'])  
//根据响应的contentType头信息,指定对应的处理方式,html的经过xmlslurper处理后返回的 是GPathResult实例  
assert html instanceof groovy.util.slurpersupport.GPathResult  
assert html.HEAD.size() == 1  
assert html.BODY.size() == 1  

  

2、POST请求

 
def http = new HTTPBuilder('http://localhost:8080/test')  
http.request(POST) {  
    uri.path = '/update'  
    body=[name:'berdy']  
    requestContentType=URLENC  
    response.success={resp->  
        assert  resp.statusLine.statusCode  
    }  
}  

  

上面代码中的body参数指定了post请求提交的参数,requestContentType指定了提交参数的处理类型,
这里指定使用urlencoder对提交的参数编码处理,若未指定就会使用request方法中指定的响应内容
处理类型,在上面的代码中并未指定响应内容的处理类型,所以就是ContentType.ANY了。在上面delegate
中提供了send()方法同时处理request content-type 和 request data


 
send URLENC, [ name : 'berdy']   
同样的HTTPBuilder也提供了一个简洁的post请求方式 

[java] view plain copy
 
def http = new HTTPBuilder('http://localhost:8080/test')  
def postBody = [name:'berdy']  
http.post(path:'/update',body:postBody,requestContentType:URLENC){resp->  
    assert resp.statusLine.statusCode == 200  
}  

  

 

3、json格式数据处理;
处理响应内容中的json数据

def http = new HTTPBuilder('http://localhost:8080/test')  
//根据responsedata中的Content-Type header,调用json解析器处理responsedata  
http.get(path:'/getJson'){resp,json->  
    println resp.status  
    json.each{  
        println it    
    }  
}  

  

处理post请求中的json数据
def http = new HTTPBuilder('http://localhost:8080/test')  
http.request( POST, JSON ) { req ->  
    uri.path='/postJson'  
    body = [  
      first : 'berdy',  
      last : 'lengfeng'  
    ]  
      
    response.success = { resp, json ->  
        // TODO process json data  
    }  
}  

  

 

也可以使用send()方法处理: 

 

def http = new HTTPBuilder('http://localhost:8080/test')  
http.request( POST, JSON ) { req ->  
    uri.path='/postJson'  
    send 'text/javascript',[body : [  
      first : 'berdy',  
      last : 'lengfeng'  
    ]]  
    response.success = { resp, json ->  
        // TODO process json data  
    }  
}  

  

另外,针对ContentType中为定义的类型,可以在parser中注册需要的处理器

 
http.parser.'text/csv' = { resp ->  
   return new CSVReader( new InputStreamReader( resp.entity.content  
            , ParserRegistry.getCharset( resp ) ) )  
}  
  
  
http.get( uri : 'http://localhost:8080/test/test.csv'  
        , contentType : 'text/csv' ) { resp, csv ->  
   assert csv instanceof CSVReader  
   // parse the csv stream here.  
}  

  

其他关于http的验证,REST支持,请参考:

http://groovy.codehaus.org/modules/http-builder/home.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM