gojs.net.http.client.Request

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

方法和属性

  1. // 构造请求
  2. // 注意这里示例变量用的是clientReq,以防止和内置的变量req产生冲突
  3. let clientReq = new gojs.net.http.client.Request("https://goedge.cn/api/boot/versions?os=linux&arch=amd64&pretty=true")
  4. // 获取请求的URL
  5. clientReq.url
  6. // 添加请求Header
  7. clientReq.addHeader(name, value)
  8. // 获取请求的所有Headers
  9. clientReq.headers
  10. // 设置请求的Content-Type
  11. // "application/x-www-form-urlencoded"是一个示例值,一般在发送POST的时候使用
  12. clientReq.setContentType("application/x-www-form-urlencoded")
  13. // 设置请求的Agent
  14. // 如果不设置的话,则默认为 "goedge-node-js/版本号"
  15. // "gojs/1.0"是一个示例
  16. clientReq.setUserAgent("gojs/1.0")
  17. // 设置请求方法
  18. // "GET"是一个示例
  19. clientReq.setMethod("GET")
  20. // 读取请求方法
  21. clientReq.method
  22. // 设置要发送的内容
  23. clientReq.setBody("内容字符串")
  24. // 读取要发送的内容
  25. clientReq.body
  26. // 发送GET请求
  27. clientReq.get()
  28. // 发送POST请求
  29. clientReq.post()

示例

读取一个JSON URL

  1. let clientReq = new gojs.net.http.client.Request("https://goedge.cn/api/boot/versions?os=linux&arch=amd64&pretty=true")
  2. clientReq.setUserAgent("gojs/1.0")
  3. let clientResp = clientReq.get()
  4. if (clientResp.error != null) {
  5. console.log("error:", clientResp.error)
  6. } else {
  7. console.log("response body:", clientResp.body, "response object:", clientResp.bodyObject)
  8. }

POST一个表单数据

  1. let clientReq = new gojs.net.http.client.Request("https://127.0.0.1/post")
  2. clientReq.setContentType("application/x-www-form-urlencoded")
  3. clientReq.setBody("name=Lily&age=20")
  4. let clientResp = clientReq.post()
  5. if (clientResp.error != null) {
  6. console.log("error:", clientResp.error)
  7. } else {
  8. console.log("status:", clientResp.status)
  9. }

POST一个JSON数据

  1. let clientReq = new gojs.net.http.client.Request("https://127.0.0.1/post")
  2. clientReq.setContentType("application/json")
  3. clientReq.setBody('{"name":"Lily", "age":20, "books":["Golang", "PHP"]}')
  4. let clientResp = clientReq.post()
  5. if (clientResp.error != null) {
  6. console.log("error:", clientResp.error)
  7. } else {
  8. console.log("status:", clientResp.status)
  9. }

PUT一个JSON数据

  1. let clientReq = new gojs.net.http.client.Request("https://127.0.0.1/post")
  2. clientReq.setContentType("application/json")
  3. clientReq.setBody('{"name":"Lily", "age":20, "books":["Golang", "PHP"]}')
  4. // 设置请求方法为PUT
  5. clientReq.setMethod("PUT")
  6. // 使用默认的HTTP客户端执行请求
  7. let clientResp = gojs.net.http.client.DefaultClient.do(clientReq)
  8. if (clientResp.error != null) {
  9. console.log("error:", clientResp.error)
  10. } else {
  11. console.log("status:", clientResp.status)
  12. }