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