2017-01-13 5 views
0

で動作します。しかし、外出先では上記を複製しようとしているPOSTは、私は自分のアプリケーションに対して、次のcurlコマンドをテストしてみたし、それが正常に返す失敗しても、カール

curl --data "username=john&password=acwr6414" http://127.0.0.1:5000/api/login 

はかなりの挑戦を証明している、Iサーバーから400不正な要求エラーを得続ける、ここのコードです:

type Creds struct { 
     Username string `json:"username"` 
     Password string `json:"password"` 
    } 

user := "john" 
pass := "acwr6414" 

    creds := Creds{Username: user, Password: pass} 
    res, err := goreq.Request{ 
     Method: "POST", 
     Uri:  "http://127.0.0.1:5000/api/login", 
     Body:  creds, 
     ShowDebug: true, 
    }.Do() 
    fmt.Println(res.Body.ToString()) 
    fmt.Println(res, err) 

私はgoreqパッケージを使用しています、私は違いはありませんで、少なくとも3つのまたは4他のパッケージを試してみました。私が手にエラーがある:あなたの囲碁コードでのJSON体が、カールとapplication/x-www-form-urlencoded体を送っている

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 
<title>400 Bad Request</title> 
<h1>Bad Request</h1> 
<p>The browser (or proxy) sent a request that this server could not understand.</p> 

答えて

6

あなたはカールでやったように手動で文字列をエンコードすることができます。

Body:  "password=acwr6414&user=john", 

それとも、きちんと身体エンコードするためにurl.Valuesを使用することができます。

creds := url.Values{} 
creds.Set("user", "john") 
creds.Set("password", "acwr6414") 

res, err := goreq.Request{ 
    ContentType: "application/x-www-form-urlencoded", 
    Method:  "POST", 
    Uri:   "http://127.0.0.1:5000/api/login", 
    Body:  creds.Encode(), 
    ShowDebug: true, 
}.Do() 
+0

ありがとうを!これは動作します! – Jonathan

関連する問題