首页 文章

POST字符串数据的golang请求

提问于
浏览
0

我可以使用POSTMAN chrome扩展来使用字符串数据执行POST请求 .

enter image description here

我需要使用 golang 代码执行相同的操作 .

但我的 Go 代码丢失字符串 INSERT INTO V SET name = 'jack', boss = #11:19 并将空数据发布到服务器 .

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

func main() {
    client := &http.Client{}
    // Why this stringData is lost and was not send with POST request?
    stringData := `INSERT INTO V SET name = 'jack', boss = #11:19`
    req, err := http.NewRequest("POST", "http://localhost:2480/command/GratefulDeadConcerts/sql", bytes.NewBufferString(stringData))
    req.SetBasicAuth("root", "1")
    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error : %s", err)
    }
    fmt.Println("resp")
    fmt.Println(ToJson(resp))

    var b bytes.Buffer
    _, err = b.ReadFrom(resp.Body)
    if err != nil {
        log.Fatal("Error : %s", err)
    }
    fmt.Println(b.String())
}

func ToJson(obj interface{}) string {
    b, err := json.MarshalIndent(&obj, "", "   ")
    if err != nil {
        fmt.Printf("Error : %s", err)
    }
    strJson := string(b)

    return strJson
}

它给出了输出:

resp
{
   "Status": "500 Internal Server Error",
   "StatusCode": 500,
   "Proto": "HTTP/1.1",
   "ProtoMajor": 1,
   "ProtoMinor": 1,
   "Header": {
      "Cache-Control": [
         "no-cache, no-store, max-age=0, must-revalidate"
      ],
      "Connection": [
         "Keep-Alive"
      ],
      "Content-Length": [
         "55"
      ],
      "Content-Type": [
         "text/plain; charset=utf-8"
      ],
      "Date": [
         "Mon Jun 08 10:47:46 MSK 2015"
      ],
      "Pragma": [
         "no-cache"
      ],
      "Server": [
         "OrientDB Server v.2.0.10 (build UNKNOWN@r; 2015-05-25 16:48:43+0000)"
      ]
   },
   "Body": {},
   "ContentLength": 55,
   "TransferEncoding": null,
   "Close": false,
   "Trailer": null,
   "Request": {
      "Method": "POST",
      "URL": {
         "Scheme": "http",
         "Opaque": "",
         "User": null,
         "Host": "localhost:2480",
         "Path": "/command/GratefulDeadConcerts/sql",
         "RawQuery": "",
         "Fragment": ""
      },
      "Proto": "HTTP/1.1",
      "ProtoMajor": 1,
      "ProtoMinor": 1,
      "Header": {
         "Authorization": [
            "Basic cm9vdDox"
         ]
      },
      "Body": {
         "Reader": {}
      },
      "ContentLength": 46,
      "TransferEncoding": null,
      "Close": false,
      "Host": "localhost:2480",
      "Form": null,
      "PostForm": null,
      "MultipartForm": null,
      "Trailer": null,
      "RemoteAddr": "",
      "RequestURI": "",
      "TLS": null
   },
   "TLS": null
}
java.lang.IllegalArgumentException: text cannot be null

如何使用GoLang使这个POST请求成功运行,就像我可以使用POSTMAN chrome扩展一样?

更新

我使用curl成功地发出了相同的POST请求 .

curl -X POST -u root:1 -H "Content-Type: application/json" --data-urlencode "INSERT INTO V SET name = 'jack', boss = #11:19"  http://localhost:2480/command/GratefulDeadConcerts/sql

它输出:

{"result":[{"@type":"d","@rid":"#9:822","@version":1,"@class":"V","name":null}]}

更新2

当然,我不应该使用 --data-urlencode 来执行 curl 命令 . 有效的curl命令是

curl -X POST -u root:1 -H "Content-Type: application/json" -d "INSERT INTO V SET name = 'jack', boss = #11:19"  http://localhost:2480/command/GratefulDeadConcerts/sql
{"result":[{"@type":"d","@rid":"#9:848","@version":1,"@class":"V","name":"jack","boss":"#11:19","@fieldTypes":"boss=x"}]}

我仍然不知道如何制作类似的GoLang POST请求 .

更新3

url.QueryEscape 没帮我 .

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
)

func main() {
    client := &http.Client{}
    // Why this stringData is lost and do not pass thgouht POST request?
    stringData := `INSERT INTO V SET name = 'jack', boss = #11:19`
    stringData = url.QueryEscape(stringData)
    req, err := http.NewRequest("POST", "http://localhost:2480/command/GratefulDeadConcerts/sql", bytes.NewBufferString(stringData))
    req.SetBasicAuth("root", "1")
    req.Header.Set("Content-Type", "Content-Type: text/plain")
    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error : %s", err)
    }
    fmt.Println("resp")
    fmt.Println(ToJson(resp))

    var b bytes.Buffer
    _, err = b.ReadFrom(resp.Body)
    if err != nil {
        log.Fatal("Error : %s", err)
    }
    fmt.Println(b.String())
}

func ToJson(obj interface{}) string {
    b, err := json.MarshalIndent(&obj, "", "   ")
    if err != nil {
        fmt.Printf("Error : %s", err)
    }
    strJson := string(b)

    return strJson
}

结果是一样的:

resp
{
   "Status": "500 Internal Server Error",
   "StatusCode": 500,
   "Proto": "HTTP/1.1",
   "ProtoMajor": 1,
   "ProtoMinor": 1,
   "Header": {
      "Cache-Control": [
         "no-cache, no-store, max-age=0, must-revalidate"
      ],
      "Connection": [
         "Keep-Alive"
      ],
      "Content-Length": [
         "55"
      ],
      "Content-Type": [
         "text/plain; charset=utf-8"
      ],
      "Date": [
         "Mon Jun 08 19:39:12 MSK 2015"
      ],
      "Pragma": [
         "no-cache"
      ],
      "Server": [
         "OrientDB Server v.2.0.10 (build UNKNOWN@r; 2015-05-25 16:48:43+0000)"
      ]
   },
   "Body": {},
   "ContentLength": 55,
   "TransferEncoding": null,
   "Close": false,
   "Trailer": null,
   "Request": {
      "Method": "POST",
      "URL": {
         "Scheme": "http",
         "Opaque": "",
         "User": null,
         "Host": "localhost:2480",
         "Path": "/command/GratefulDeadConcerts/sql",
         "RawQuery": "",
         "Fragment": ""
      },
      "Proto": "HTTP/1.1",
      "ProtoMajor": 1,
      "ProtoMinor": 1,
      "Header": {
         "Authorization": [
            "Basic cm9vdDox"
         ],
         "Content-Type": [
            "Content-Type: text/plain"
         ]
      },
      "Body": {
         "Reader": {}
      },
      "ContentLength": 60,
      "TransferEncoding": null,
      "Close": false,
      "Host": "localhost:2480",
      "Form": null,
      "PostForm": null,
      "MultipartForm": null,
      "Trailer": null,
      "RemoteAddr": "",
      "RequestURI": "",
      "TLS": null
   },
   "TLS": null
}
java.lang.IllegalArgumentException: text cannot be null

另外,我在 curl 命令中将content-type更改为 text/plain .

curl -X POST -u root:1 -H "Content-Type: text/plain" -d "INSERT INTO V SET name = 'jack', boss = #11:19"  http://localhost:2480/command/GratefulDeadConcerts/sql
{"result":[{"@type":"d","@rid":"#9:858","@version":1,"@class":"V","name":"jack","boss":"#11:19","@fieldTypes":"boss=x"}]}

结果是一样的, curl 没问题,但 golang POST不行 .

更新4

我想做什么?我正在实现OrientDB REST-interface来执行来自 GO 应用程序的查询 .

1 回答

  • 0

    阅读文档显然有帮助 . 从OrientDB文档文档[1]:

    所有请求必须包含以下两个 Headers :'Accept-Encoding':'gzip,deflate'
    'Content-Length':<content-length>
    其中是请求的正文长度 .

    并且您不设置Accept-Encoding标头 . 最有可能这就是你所需要的(而不是逃避身体) .

    [1] http://orientdb.com/docs/last/orientdb.wiki/OrientDB-REST.html#headers

相关问题