一、使用 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]
}