dongzhitao4839 2014-03-11 02:37
浏览 8
已采纳

PHP vs Golang http调用得到不同的结果

I am trying to implement the following PHP code in Google App Engine Go:

<?php

function api_query(array $req = array()) {
        $key = '90294318da0162b082c3d27126be80c3873955f9';

        $req['method'] = 'getinfo';
        $req['nonce'] = 1394503747386411;

        // generate the POST data string
        $post_data = http_build_query($req, '', '&');
        $sign = '75da1e3ff750286bf73d03197f1b779fbfff963fd7402941ae326509a6615eacb839b44f236b4d5ee6cff39321e7b35e9563a9a2075e99df0f4ee3b732999348';

        // generate the extra headers
        $headers = array(
                'Sign: '.$sign,
                'Key: '.$key,
        );

        // our curl handle (initialize if required)
        static $ch = null;
        if (is_null($ch)) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; Cryptsy API PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
        }
        curl_setopt($ch, CURLOPT_URL, 'https://api.cryptsy.com/api');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        // run the query
        $res = curl_exec($ch);

        if ($res === false) throw new Exception('Could not get reply: '.curl_error($ch));
        $dec = json_decode($res, true);
        if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');

        echo "<pre>".print_r($dec, true)."</pre>";
        return $dec;
}

api_query();

When executed, the code returns a JSON array of values. I tried implementing the same code in Golang:

func PrivateCall(c appengine.Context) (map[string]interface{}, error) {
    AuthAPI := "https://api.cryptsy.com/api"
    APIKey := "90294318da0162b082c3d27126be80c3873955f9"
    tr := urlfetch.Transport{Context: c}
    values := url.Values{}
    values.Set("method", "getinfo")
    values.Set("nonce", "1394503747386411")

    signature := "75da1e3ff750286bf73d03197f1b779fbfff963fd7402941ae326509a6615eacb839b44f236b4d5ee6cff39321e7b35e9563a9a2075e99df0f4ee3b732999348"

    req, err := http.NewRequest("POST", AuthAPI+"?"+values.Encode(), nil)
    if err != nil {
        c.Infof("API - Call - error 2 - %s", err.Error())
        return nil, err
    }
    req.Header.Set("Key", APIKey)
    req.Header.Set("Sign", signature)

    c.Infof("req - %v", req)
    resp, err := tr.RoundTrip(req)
    if err != nil {
        c.Errorf("API post error: %s", err)
        return nil, err
    }
    defer resp.Body.Close()
    //reading response
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        c.Errorf("API read error: could not read body: %s", err)
        return nil, err
    }
    result := make(map[string]interface{})
    //unmarshalling JSON response
    err = json.Unmarshal(body, &result)
    if err != nil {
        c.Infof("Unmarshal: %v", err)
        c.Infof("%s", body)
        return nil, err
    }
    return result, nil
}

I am getting an error saying "Unable to Authorize Request - Check Your Post Data". Does anyone see what could've caused this error? At the moment my best guess is that perhaps the request header in Go is a map[string][]string, while in PHP it appears to be an array...

  • 写回答

2条回答 默认 最新

  • dougui4325 2014-03-11 08:45
    关注

    As suggested by LeGEC, you're putting the POST data onto the end of the URL as if it were a GET request.

    Try replacing

    values := url.Values{}
    values.Set("method", "getinfo")
    values.Set("nonce", "1394503747386411")
    
    signature := "75da1e3ff750286bf73d03197f1b779fbfff963fd7402941ae326509a6615eacb839b44f236b4d5ee6cff39321e7b35e9563a9a2075e99df0f4ee3b732999348"
    
    req, err := http.NewRequest("POST", AuthAPI+"?"+values.Encode(), nil)
    

    with

    data := struct {
        method string
        nonce  string
    }{
        "getinfo",
        "1394503747386411",
    }
    signature := "75da1e3ff750286bf73d03197f1b779fbfff963fd7402941ae326509a6615eacb839b44f236b4d5ee6cff39321e7b35e9563a9a2075e99df0f4ee3b732999348"
    postData, err := json.Marshal(data)
    if err != nil {
        return nil, err
    }
    buf := bytes.NewBuffer(postData)
    req, err := http.Post(AuthAPI, "application/json", buf)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。