Groovy如何使用request
时间: 2024-06-09 13:10:49 浏览: 201
grooid-tools:使用 Groovy 帮助 Android 开发的工具
Groovy可以使用Java的HttpURLConnection或Apache HttpComponents来发送HTTP请求。其中HttpURLConnection是Java自带的HTTP客户端,而Apache HttpComponents是一个第三方库。
以下是使用HttpURLConnection发送GET请求的示例代码:
```
def url = new URL("http://example.com/api")
def conn = url.openConnection()
conn.setRequestMethod("GET")
def responseCode = conn.getResponseCode()
if (responseCode == HttpURLConnection.HTTP_OK) {
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
def response = new StringBuffer()
String line
while ((line = reader.readLine()) != null) {
response.append(line)
}
reader.close()
println(response.toString())
} else {
println("Failed to fetch data from server")
}
```
以下是使用Apache HttpComponents发送POST请求的示例代码:
```
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.5.13')
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
def httpClient = new DefaultHttpClient()
def postMethod = new HttpPost("http://example.com/api")
postMethod.setHeader("Content-Type", "application/json")
def requestBody = [
name: "John Doe",
age: 30
]
def requestJson = new JsonBuilder(requestBody).toString()
postMethod.setEntity(new StringEntity(requestJson))
def response = httpClient.execute(postMethod)
def entity = response.getEntity()
if (entity != null) {
def responseJson = EntityUtils.toString(entity)
println(responseJson)
}
```
阅读全文