POST字符串数据的golang请求

时间:2015-06-08 07:01:34

标签: rest go

我可以使用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

另外,我在text/plain命令中将内容类型更改为curl

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 :(得分:0)

阅读文档显然有帮助。来自OrientDB文档文档[1]:

  

所有请求必须包含以下两个标题:

'Accept-Encoding': 'gzip,deflate'
'Content-Length': <content-length>
     

请求的正文长度。

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

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