EternallyCurious
EternallyCurious

Reputation: 2415

Cant connect to survey monkey API

I am trying to connect to the survey monekey API with this code, which is not working. It says "Invalid API key" even though I got the API from the API console.

 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();
        }
    }

Here's the error:

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"}

I just got this url from the API console.

Upvotes: 0

Views: 470

Answers (2)

Ryan Dugan
Ryan Dugan

Reputation: 613

That particular error is generated when an empty string is sent for the POST data. The API expects an empty object at minimum ("{}"). If the issue pointed out by Miles above was just a typo (using 'getRequestProperty' instead of 'setRequestProperty',) check if toString on an empty JSONObject is returning "" or "{}".

Upvotes: 0

Miles Cederman-Haysom
Miles Cederman-Haysom

Reputation: 1134

Ensure you are using the API key associated with your developer account registered at http://developer.surveymonkey.com, not the sample API key the console uses to let you try requests. The sample api key is not meant to be used with apps, only on the API console.

Upvotes: 1

Related Questions