1

我正在尝试发出“Freebusy”请求以连接到 Google Calendar API。目前我坚持格式化http POST。我收到一个错误:

{
  "error": {
   "errors": [
    {
     "domain": "global",
     "reason": "parseError",
     "message": "Parse Error"
    }
   ],
   "code": 400,
   "message": "Parse Error"
  }
}

我正在尝试像这样格式化请求:

{
  "timeMin": datetime,
  "timeMax": datetime,
  "timeZone": string,
  "groupExpansionMax": integer,
  "calendarExpansionMax": integer,
  "items": [
    {
      "id": string
    }
  ]
}

目前正在这样做以格式化它:

String[] stringPairs = new String[]{
            "timeMin",       date1,
            "timeMax",       date2,
            "items[]",       calendarID,
            "timezone",      "Canada/Toronto"};

//Create an HTTP post request
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("HostULR");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(stringPairs.length/2 - 1);

for (int i = 0; i < stringPairs.length; i += 2) {
    nameValuePairs.add(new BasicNameValuePair(stringPairs[i], stringPairs[i+1]));
}

post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
org.apache.http.HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();

我相信我搞砸的部分是"items"部分。任何帮助,将不胜感激。

4

2 回答 2

0

不知道这对 java 是否正确,但在 C 中,您只需将另一个 json 插入其中即可生成复杂的 json。

也许这个网站可以帮助你。

https://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-3_-_Encode_a_JSON_object_-_Using_Map

编辑:我注意到表单是一个对象数组......所以正确的实现应该是这样的。

  JSONObject obj=new JSONObject();
  obj.put("ID", string);

  JSONArray list = new JSONArray();

  list.add(obj);

  JSONObject jsonObj = new JSONObject();{
            object.put("timeMin", date1)
            ....

另外,我不知道这个代码......

"timezone",      "Canada/Toronto"}, accessToken );

对于 json 对象,它通常 {} 象征着 json 对象 [] 这些是数组。

编辑 2:创建 JSON 后执行此操作

StringEntity entity = new StringEntity(json.toString());
                     entity.setContentType("application/json;charset=UTF-8");
                     entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
                     request.setHeader("Accept", "application/json");
                     request.setEntity(entity); 

                     HttpResponse response =null;
                     DefaultHttpClient httpClient = new DefaultHttpClient();

                     HttpConnectionParams.setSoTimeout(httpClient.getParams(), Constants.ANDROID_CONNECTION_TIMEOUT*1000); 
                     HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),Constants.ANDROID_CONNECTION_TIMEOUT*1000); 
                     try{

                     response = httpClient.execute(request); 
                     }
                     catch(SocketException se)
                     {
                         Log.e("SocketException", se+"");
                         throw se;
                     }




InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while((line = reader.readLine()) != null){
    sb.append(line);
于 2013-08-07T17:13:33.060 回答
0

如何创建一个与您尝试发送的 json 匹配的类并在其上放置一个类,然后使用GsonArrayList<String>之类的 Json 解析器并使用 a发送发布请求,这是一个示例:StringEntity

public class JsonTest extends AsyncTask<GoogleCalendarJson, Void, String> {
private HttpClient client;
private HttpPost request;
private HttpResponse response;
private Activity activity;

public JsonTest(Activity a){
    activity = a;
}

@Override
public String doInBackground(GoogleCalendarJson... object){
    client = new DefaultHttpClient();
    request = new HttpPost("YOUR URL HERE");
    StringBuffer b = new StringBuffer("");
    String json = new Gson().toJson(object[0]);
    InputStream is = null;
    BufferedReader br = null;
    try{
        StringEntity se = new StringEntity(json);
        request.setHeader(HTTP.CONTENT_TYPE, "application/json");
        request.setEntity(se);
        response = client.execute(request);
        is = response.getEntity().getContent();
        br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while(((line = br.readLine()) != null)){
            b.append(line);
        }
        br.close();
    }catch(IOException e){
        b.append(e.getMessage());
    }

    return b.toString();
}
@Override
public void onPostExecute(final String result){
    activity.runOnUiThread(new Runnable(){
        @Override
        public void run(){
            TextView t = (TextView)activity.findViewById(R.id.result);
            t.setText(result);
        }
    });
}
}

configuration是 aplain old java object并且它没有对另一个configuration对象的引用,configuration可以有一个ArrayList<String>,我不确定你是否可以ArrayList<Item>在它上面有一个你可以尝试它,另外,如果你可以使用HttpURLConnection而不是 Apache 的 HttpClient '在这里为 post-gingerbread 应用程序重新编程是WHY http://android-developers.blogspot.com/2011/09/androids-http-clients.html,希望这对任何人都有帮助。PD:我没有为下面的代码使用 IDE,如果出现错误,很抱歉(我现在没有 Android Studio @home,我用 netbeans 格式化了这段代码:p)。

编辑:为了澄清起见,这个 AsyncTask 应该在 UI 线程中运行(比如在 Activity 中),如下所示:

JsonTest test = new JsonTest(this); //here we pass the Activity
test.execute(new GoogleCalendarJson()); //this is the object we get in 'object0]'

编辑 2:新代码实际上运行良好让我给你举个 GoogleCalendarJson 类的例子:

GoogleCalendarJson 类(必须有 getter/setter):

public class GoogleCalendarJson {
private String timeMin, timeMax, timezone;
private int groupExpanxionMaxm, calendarExpansionMax;
private ArrayList<Item> items;

public GoogleCalendarJson() {
}
}

物品类别(与 g/s 相同):

public class Item {
private String id;

public Item() {
}
}

使用 Gson 生成的 Json 示例:

{"timezone":"someTimezone","timeMin":"min","items":
[{"id":"someID"}],"timeMax":"max","groupExpanxionMaxm":2,"calendarExpansionMax":1}

要检查 Json 结构,您可以将上面的 json 粘贴到此处JsonValidator 以测试此代码,您需要一个至少有一个带有 id 的 TextView 的 Activity:result

于 2013-08-08T01:22:20.150 回答