surveymonkey API调用返回状态代码3-无效请求

时间:2014-03-07 21:13:20

标签: java client httpurlconnection surveymonkey

编辑:感谢您的建议。我更改了代码以实现json对象而不是字符串并在正文中发送

这就是我试图从调查猴子那里得到的细节。我得到的响应代码为200,但无法获得我需要的数据。有人可以让我知道我在做错了什么。 可能是这个网址可以帮助指定我正在尝试做什么 https://developer.surveymonkey.com/mashery/requests_responses 这是o / p我得到{“status”:3,“errmsg”:“没有JSON对象可以被解码:第1行第0列(char 0)”}

    package surveydetails;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class Surveydetails {

        public static void main(String args []) {       
        String url = "https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=myapikey";                    
                    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.setRequestMethod("POST");


conn.setRequestProperty("Authorization", "bearer myauthtoken"); 
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();
                    }

                }
}

1 个答案:

答案 0 :(得分:0)

POST正文的JSON编码无效。

您的代码String body=" '{\"fields\":[\"title\"]}'";

应为String body="{\"fields\":[\"title\"]}";

我建议在编码JSON对象时使用像json-simple这样的JSON库以避免无效的JSON。随着应用程序的发展,库也将更加灵活。