Groovy 发送 HTTP 请求

build.gradle里面想进行网络请求应该如何操作

get非常的简单

def res1 = new URL('https://httpbin.org/ip').text
// or 
def res2 = 'https://httpbin.org/ip'.toURL().text

post可以这么用

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

/**
 * 发送 HTTP POST 请求
 * @param url 请求的网址
 * @param data 请求所需的参数,可选
 * @param is_json 请求参数类型是否为 json 格式
 * @return Map
 */
def http_post(url, data = null, isJson = false) {
    def conn = new URL(url).openConnection()
    conn.setRequestMethod("POST")
    if (data) {
        if (isJson) {
            conn.setRequestProperty("Content-Type", "application/json")
            data = JsonOutput.toJson(data)
        }

        // 输出请求参数
        conn.doOutput = true
        def writer = new OutputStreamWriter(conn.outputStream)
        writer.write(data)
        writer.flush()
        writer.close()
    }

    if(isJson){
        def json = new JsonSlurper()
        def result = json.parseText(conn.content.text)
        return result

    }else {
        return conn.content.text
    }

}

def res = http_post('https://httpbin.org/post', '{"name": "John", "age": 34}', true)
print("输出")
println(res)

输出结果

输出{args={}, data="{\"name\": \"John\", \"age\": 34}", files={}, form={}, headers={Accept=text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2, Content-Length=35, Content-Type=application/json, Host=httpbin.org, User-Agent=Java/1.8.0_302, X-Amzn-Trace-Id=Root=1-618f4d5c-42749b3b6a0e9bf82acdc6a1}, json={"name": "John", "age": 34}, origin=203.218.243.233, url=https://httpbin.org/post}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值