无法连接到调查猴子API

时间:2014-10-28 17:59:29

标签: surveymonkey

我正在尝试使用此代码连接到调查monekey API,但该代码无效。它说“无效的API密钥”,即使我从API控制台获得了API。

 public void fetch() {
        String url = "https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=" + apiKey;
        System.out.println("request being sent");
        System.out.println(url);
        JSONObject obj = new JSONObject();
        try {
            // byte[] postDataBytes = obj.toJSONString().getBytes("UTF-8");
            URL ourl = new URL(url.toString());
            HttpURLConnection conn = (HttpURLConnection) ourl.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Authorization", "bearer " + accessToken);
            conn.setRequestProperty("Content-Type", "application/json");

            conn.getRequestProperty(obj.toString().getBytes("UTF-8").toString());

            int k = conn.getResponseCode();
            System.out.println("The response code received is " + k);
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;

            System.out.println("Output from Server .... \n");

            output = br.readLine();
            System.out.println(output);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这是错误:

request being sent
https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=---API-KEY----
The response code received is 200
Output from Server .... 
{"status":3,"errmsg":"Expected object or value"}

我刚从API控制台获取此URL。

2 个答案:

答案 0 :(得分:1)

确保您使用的是与您在http://developer.surveymonkey.com注册的开发者帐户相关联的API密钥,而不是控制台用来尝试请求的示例API密钥。示例api密钥不适用于应用程序,仅适用于API控制台。

答案 1 :(得分:0)

为POST数据发送空字符串时会生成该特定错误。 API至少需要一个空对象(" {}")。如果上面的Miles指出的问题只是一个错字(使用' getRequestProperty'而不是' setRequestProperty',)检查空JSONObject上的toString是否返回"&#34 ;或" {}"。