2014-10-28 51 views
0

我正尝试使用此代码连接到调查monekey API,该代码不工作。它说“无效的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控制台这个网址。

回答

0

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

1

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

+0

谢谢!但我仍然遇到错误。上面更新的问题。 – EternallyCurious 2014-10-29 16:58:35

+0

它看起来不像你发送JSON对象作为一个字符串。 – 2014-10-29 22:49:38

+0

我想我在这部分发送一个对象作为字符串:conn.setRequestProperty(“Authorization”,“bearer”+ accessToken); conn.setRequestProperty(“Content-Type”,“application/json”); conn.getRequestProperty(obj.toString()。getBytes(“UTF-8”)。toString());你还期望什么?你能特意回答吗? – EternallyCurious 2014-10-30 16:13:11