groovy http请求
时间: 2023-10-05 22:11:07 浏览: 67
在Groovy中发送HTTP请求的方式有多种。一种常见的方法是使用Groovy内置的REST/HTTP客户端库。你可以使用以下代码片段来发送GET请求并获取响应:
```groovy
@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.1')
import groovyx.net.http.HTTPBuilder
def http = new HTTPBuilder('http://example.com')
http.request(GET) {
response.success = { resp, reader ->
// 处理响应数据
println resp.statusLine
println reader.text
}
}
```
如果你需要发送POST请求,你可以使用以下代码片段:
```groovy
@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.1')
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
def http = new HTTPBuilder('http://example.com')
http.request(POST, ContentType.JSON) {
body = [key1: 'value1', key2: 'value2']
response.success = { resp, reader ->
// 处理响应数据
println resp.statusLine
println reader.text
}
}
```
请注意,在使用这些代码之前,你需要先安装HTTPBuilder库。你可以通过在代码中添加`@Grab`注解来自动下载所需的依赖。
参考文献:
- [Groovy built-in REST/HTTP client? - Stack Overflow](https://stackoverflow.com/questions/711253/groovy-built-in-rest-http-client)
- [How to get the REST response in Groovy? - Stack Overflow](https://stackoverflow.com/questions/1509915/how-to-get-the-rest-response-in-groovy)
- [Executing an HTTP POST request - Groovy 2 Cookbook](http://groovy.codehaus.org/Executing+an+HTTP+POST+request)
- [Java/Groovy disable SSL verification](https://groovy-lang.org/http-builder/apidocs/groovyx/net/http/HttpBuilder.html)
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)