gojs.net.http.client.Request

HTTP客户端请求对象,用来构造即将发送的请求。

方法和属性

// 构造请求
// 注意这里示例变量用的是clientReq,以防止和内置的变量req产生冲突
let clientReq = new gojs.net.http.client.Request("https://goedge.cn/api/boot/versions?os=linux&arch=amd64&pretty=true")

// 获取请求的URL
clientReq.url

// 添加请求Header
clientReq.addHeader(name, value)

// 获取请求的所有Headers
clientReq.headers

// 设置请求的Content-Type
// "application/x-www-form-urlencoded"是一个示例值,一般在发送POST的时候使用
clientReq.setContentType("application/x-www-form-urlencoded")

// 设置请求的Agent
// 如果不设置的话,则默认为 "goedge-node-js/版本号"
// "gojs/1.0"是一个示例
clientReq.setUserAgent("gojs/1.0")

// 设置请求方法
// "GET"是一个示例
clientReq.setMethod("GET")

// 读取请求方法
clientReq.method

// 设置要发送的内容
clientReq.setBody("内容字符串")

// 读取要发送的内容
clientReq.body

// 发送GET请求
clientReq.get()

// 发送POST请求
clientReq.post()

示例

读取一个JSON URL

let clientReq = new gojs.net.http.client.Request("https://goedge.cn/api/boot/versions?os=linux&arch=amd64&pretty=true")
clientReq.setUserAgent("gojs/1.0")

let clientResp = clientReq.get()
if (clientResp.error != null) {
	console.log("error:", clientResp.error)
} else {
	console.log("response body:", clientResp.body, "response object:", clientResp.bodyObject)
}

POST一个表单数据

let clientReq = new gojs.net.http.client.Request("https://127.0.0.1/post")
clientReq.setContentType("application/x-www-form-urlencoded")
clientReq.setBody("name=Lily&age=20")

let clientResp = clientReq.post()
if (clientResp.error != null) {
	console.log("error:", clientResp.error)
} else {
	console.log("status:", clientResp.status)
}

POST一个JSON数据

let clientReq = new gojs.net.http.client.Request("https://127.0.0.1/post")
clientReq.setContentType("application/json")
clientReq.setBody('{"name":"Lily", "age":20, "books":["Golang", "PHP"]}')

let clientResp = clientReq.post()
if (clientResp.error != null) {
	console.log("error:", clientResp.error)
} else {
	console.log("status:", clientResp.status)
}

PUT一个JSON数据

let clientReq = new gojs.net.http.client.Request("https://127.0.0.1/post")
clientReq.setContentType("application/json")
clientReq.setBody('{"name":"Lily", "age":20, "books":["Golang", "PHP"]}')

// 设置请求方法为PUT
clientReq.setMethod("PUT")

// 使用默认的HTTP客户端执行请求
let clientResp = gojs.net.http.client.DefaultClient.do(clientReq)
if (clientResp.error != null) {
	console.log("error:", clientResp.error)
} else {
	console.log("status:", clientResp.status)
}