Gradle http Post 文件上传 、Get

 一、使用 HttpURLConnection

// post文字
static def httpPostText(String url, String text) {
    return doRequest(url, { HttpURLConnection post ->
        post.setRequestProperty("content-length", text.length().toString())
        post.setRequestProperty("content-type", "application/x-www-form-urlencoded")
    }) { DataOutputStream dos ->
        dos.writeBytes(text)
    }
}

// 上传文件
static def httpUploadFile(String url, File fileUpload) {
    String boundary = UUID.randomUUID().toString()
    return doRequest(url, { HttpURLConnection post ->
        post.setRequestProperty("content-length", fileUpload.size().toString())
        post.setRequestProperty("content-type", "multipart/form-data;boundary=$boundary")
    }) { DataOutputStream dos ->
        dos.writeBytes("--$boundary\r\n")
        dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"${fileUpload.name}\"\r\n\r\n")
        fileUpload.eachByte(1024) { byte[] bytes, Integer len -> dos.write(bytes, 0, len) }
        dos.writeBytes("\r\n--$boundary--\r\n")
    }
}

/**
 * cloOnRequest: 填充请求参数
 * cloOnPost: 具体的post 内容
 **/
static def doRequest(String url, Closure cloOnRequest, Closure cloOnPost) {
    HttpURLConnection post = null
    int respCode = 0
    String respText = ""
    try {
        post = new URL(url).openConnection()
        post.requestMethod = cloOnPost != null? "POST": "GET"
        post.useCaches = false
        post.doOutput = true
        post.readTimeout = 10000
        post.connectTimeout = 10000
        post.setRequestProperty("cache-control", "no-cache")
        // 添加其他的参数

        if (cloOnRequest != null) {
            cloOnRequest.call(post)
        }
        if (cloOnPost != null) {
            DataOutputStream dos = new DataOutputStream(post.outputStream)
            cloOnPost.call(dos)
            dos.flush()
            dos.close()
        }
        respCode = post.responseCode
        respText = post.getInputStream().text.trim()
    } finally {
        if (post != null) post.disconnect()
    }

    return ["code": respCode, "text": respText]
}

二、使用 apache httpclient

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.apache.httpcomponents:httpclient:4.5.9'
        classpath 'org.apache.httpcomponents:httpmime:4.5.9'
    }
}

import org.apache.http.HttpEntity
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.util.EntityUtils
import org.apache.http.entity.mime.MultipartEntityBuilder

static def httpUploadFile(String url, File fileUpload) {
    return doRequest(url, MultipartEntityBuilder.create().addBinaryBody("file", fileUpload).build())
}

static def httpPostText(String url, String name, String text) {
    return doRequest(url, MultipartEntityBuilder.create().addTextBody(name, text).build())
}

static def doRequest(String url, HttpEntity requestEntity) {
    CloseableHttpResponse response = null
    CloseableHttpClient httpClient = null
    int respCode = 0
    String respText = ""
    try {
        httpClient = HttpClientBuilder.create().build()
        HttpRequestBase request
        if (requestEntity == null) {
            request = new HttpGet(url)
        } else {
            request = new HttpPost(url)
            request.setEntity(requestEntity)
        }
        //  添加header: request.setHeader()
        response = httpClient.execute(request)
        def entity = response.getEntity()
        respCode = response.statusLine.statusCode
        respText = EntityUtils.toString(response.getEntity(), "utf-8").trim()
        EntityUtils.consume(entity)
    } finally {
        if (httpClient != null) httpClient.close()
        if (response != null) response.close()
    }

    return ["code": respCode, "text": respText]
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值