获取Lifelog API结果

时间:2016-05-03 10:06:42

标签: android android-volley sony sony-lifelog-api

我正在尝试使用Lifelog的API,我编写了这部分代码:

.
.
.
//MAIN ACTIVITY
private void scaricaDati(){

    token = spref.getString("access_token");

    Log.i(TAG, "(scaricaDati) token = " + token);

    String tag_json_obj = "json_obj_req";

    String url = "https://platform.lifelog.sonymobile.com/v1/users/me/activities";
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.i("MainActivity response ", response.toString());

                    try {
                        Log.i(TAG,"Ottieni Dati");
                        JSONArray result=response.getJSONArray("result");
                        Log.i("MainActivity result",result.toString());
                        for (int i = 0; i < result.length(); i++) {
                            JSONObject jsonobject = result.getJSONObject(i);


                            String startTime = jsonobject.getString("startTime");
                            Log.i("MainActivity start time",startTime.toString());
                            String endTime = jsonobject.getString("endTime");
                            Log.i("MainActivity end time",endTime.toString());


                        }



                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("MainActivity ", "Error: " + error.getMessage());

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("start_time", "2016-04-07T17:00:00.000Z");
            params.put("end_time", "2016-04-07T18:00:00.000Z");
            params.put("type", "physical:walk");
            return params;
        }


        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "Bearer "+ token);
            headers.put("Accept", "application/json");
            //headers.put("Accept-Encoding", "gzip");
            //headers.put("Content-Encoding", "gzip");
            return headers;
        }
    };

    // Adding request to request queue
    ApplicationController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
.
.
.

//LIFELOG CLASS WITH THE "DOLOGIN" METHOD


public static final int LOGINACTIVITY_REQUEST_CODE = 2231;

public static final String API_BASE_URL = "https://platform.lifelog.sonymobile.com";

public static final String LIFELOG_PREFS = "lifelog_prefs";
static String client_id = "";
static String client_secret = "";
static String login_scope = "";
static String callback_url = "";
static String auth_token = "";

public static String getClient_id() {
    return client_id;
}

public static String getClient_secret() {
    return client_secret;
}

public static String getCallback_url() {
    return callback_url;
}

public static String getAuth_token() {
    return auth_token;
}

public static void initialise(String id, String secret, String callbackUrl) {
    client_id = id;
    client_secret = secret;
    callback_url = callbackUrl;
    setScope(Scopes.PROFILE_READ, Scopes.ACTIVITIES_READ, Scopes.LOCATIONS_READ);
}

public static String getScope() {
    return login_scope;
}

public static void setScope(String... scopes) {
    login_scope = "";
    for (String scope : scopes) {
        if (TextUtils.isEmpty(login_scope)) {
            login_scope = scope;
        } else {
            login_scope += "+" + scope;
        }
    }
}


public static void doLogin(Activity activity) {
    Intent loginIntent = new Intent(activity, LoginActivity.class);
    activity.startActivityForResult(loginIntent, LOGINACTIVITY_REQUEST_CODE);
}

public static void checkAuthentication (Context context, final OnAuthenticationChecked oac) {
    SecurePreferences securePreferences = new SecurePreferences(
            context,
            LIFELOG_PREFS,
            getClient_secret(),
            true
    );
    if (securePreferences.containsKey(GetAuthTokenTask.AUTH_ACCESS_TOKEN)) {
        auth_token = securePreferences.getString(GetAuthTokenTask.AUTH_ACCESS_TOKEN);
        long expires_in = Long.valueOf(securePreferences.getString(GetAuthTokenTask.AUTH_EXPIRES_IN));
        if (expires_in > 120) {
            oac.onAuthChecked(true);
        } else {
            RefreshAuthTokenTask ratt = new RefreshAuthTokenTask(context);
            ratt.refreshAuth(new RefreshAuthTokenTask.OnAuthenticatedListener() {
                @Override
                public void onAuthenticated(String token) {
                    auth_token = token;
                    oac.onAuthChecked(true);
                }
            });
        }
    }
    oac.onAuthChecked(false);
}

public interface OnAuthenticationChecked {
    void onAuthChecked(boolean authenticated);
}

public static class Scopes {
    public static final String PROFILE_READ = "lifelog.profile.read";
    public static final String ACTIVITIES_READ = "lifelog.activities.read";
    public static final String LOCATIONS_READ = "lifelog.locations.read";
}

.
.
.
//GetAuthTokenTask class

private static final String TAG = "LifeLog:GetAuthToken";
private static final String OAUTH2_URL = "https://platform.lifelog.sonymobile.com/oauth/2/token";
public static final String AUTH_ACCESS_TOKEN = "access_token";
public static final String AUTH_EXPIRES_IN = "expires_in";
public static final String AUTH_REFRESH_TOKEN = "refresh_token";
public static final String AUTH_TOKEN_TYPE = "token_type";
public static final String AUTH_REFRESH_TOKEN_EXPIRES_IN = "refresh_token_expires_in";
private final static String PARAM_CLIENT_ID = "client_id";
private final static String PARAM_CLIENT_SECRET = "client_secret";
private final static String PARAM_GRANT_TYPE = "grant_type";
private final static String PARAM_CODE = "code";
private final Context mContext;
private OnAuthenticatedListener onAuthenticatedListener;
public GetAuthTokenTask(Context context) {
    this.mContext = context;
}

public void getAuth(final String authCode, OnAuthenticatedListener oal) {
    onAuthenticatedListener = oal;

    final String authRequestBody =
            PARAM_CLIENT_ID + "=" + LifeLog.getClient_id() + "&"
                    + PARAM_CLIENT_SECRET + "=" + LifeLog.getClient_secret() + "&"
                    + PARAM_GRANT_TYPE + "=" + "authorization_code" + "&"
                    + PARAM_CODE + "=" + authCode;

    JsonObjectRequest authRequest = new JsonObjectRequest(Request.Method.POST,
            OAUTH2_URL,
            (JSONObject)null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jObj) {
                    try {

                        SecurePreferences spref = new SecurePreferences(mContext,
                                LifeLog.LIFELOG_PREFS, LifeLog.getClient_secret(), true);
                        spref.put(AUTH_ACCESS_TOKEN, jObj.getString(AUTH_ACCESS_TOKEN));
                        spref.put(AUTH_EXPIRES_IN, jObj.getString(AUTH_EXPIRES_IN));
                        spref.put(AUTH_TOKEN_TYPE, jObj.getString(AUTH_TOKEN_TYPE));
                        spref.put(AUTH_REFRESH_TOKEN, jObj.getString(AUTH_REFRESH_TOKEN));
                        spref.put(AUTH_REFRESH_TOKEN_EXPIRES_IN,
                                  jObj.getString(AUTH_REFRESH_TOKEN_EXPIRES_IN));
                        if (Debug.isDebuggable(mContext)) {
                            Log.d("TOKEN", jObj.getString(AUTH_ACCESS_TOKEN));
                            Log.d("REFRESH TOKEN", jObj.getString(AUTH_REFRESH_TOKEN));

                        }
                        if (onAuthenticatedListener != null) {
                            onAuthenticatedListener.onAuthenticated(jObj.getString(AUTH_ACCESS_TOKEN));
                        }
                    } catch (JSONException e) {
                        if (onAuthenticatedListener != null) {
                            onAuthenticatedListener.onError(e);
                        }
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    if (onAuthenticatedListener != null) {
                        onAuthenticatedListener.onError(volleyError);
                    }
                }
            }
    ) {
        @Override
        public String getBodyContentType() {
            return String.format("application/x-www-form-urlencoded; charset=%s", new Object[]{"utf-8"});
        }

        @Override
        public byte[] getBody() {
            return authRequestBody.getBytes(Charset.forName("utf-8"));
        }

    };
    VolleySingleton.getInstance(mContext).addToRequestQueue(authRequest);
}

public interface OnAuthenticatedListener {
    void onAuthenticated(String authToken);
    void onError(Exception e);
}

.
.
.

//RefreshAuthTokenTask class

    public static final String TAG = "LifeLog:RefreshAuth";
public static final String OAUTH2_URL = "https://platform.lifelog.sonymobile.com/oauth/2/refresh_token";
public static final String AUTH_ACCESS_TOKEN = "access_token";
public static final String AUTH_ISSUED_AT = "issued_at";
public static final String AUTH_EXPIRES_IN = "expires_in";
public static final String AUTH_EXPIRES = "expires";
public static final String AUTH_REFRESH_TOKEN = "refresh_token";
static String PARAM_CLIENT_ID = "client_id";
static String PARAM_CLIENT_SECRET = "client_secret";
static String PARAM_GRANT_TYPE = "grant_type";
static String PARAM_REFRESH_TOKEN = "refresh_token";
private Context mContext;
private OnAuthenticatedListener onAuthenticatedListener;
public RefreshAuthTokenTask(Context context) {
    this.mContext = context;
}

public void refreshAuth(OnAuthenticatedListener oal) {
    onAuthenticatedListener = oal;
    final SecurePreferences spref = new SecurePreferences(mContext,
            LifeLog.LIFELOG_PREFS, LifeLog.getClient_secret(), true);

    final String refreshAuthBody =
            PARAM_CLIENT_ID + "=" + LifeLog.getClient_id() + "&"
                    + PARAM_CLIENT_SECRET + "=" + LifeLog.getClient_secret() + "&"
                    + PARAM_GRANT_TYPE + "=" + "refresh_token" + "&"
                    + PARAM_REFRESH_TOKEN + "=" + spref.getString(AUTH_REFRESH_TOKEN);

    Log.d(TAG, refreshAuthBody);

    JsonObjectRequest authRequest = new JsonObjectRequest(Request.Method.POST,
            OAUTH2_URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jObj) {
                    try {

                        spref.put(AUTH_ACCESS_TOKEN, jObj.getString(AUTH_ACCESS_TOKEN));
                        spref.put(AUTH_EXPIRES_IN, jObj.getString(AUTH_EXPIRES_IN));
                        spref.put(AUTH_EXPIRES, jObj.getString(AUTH_EXPIRES));
                        spref.put(AUTH_ISSUED_AT, jObj.getString(AUTH_ISSUED_AT));
                        spref.put(AUTH_REFRESH_TOKEN, jObj.getString(AUTH_REFRESH_TOKEN));
                        Log.d("NEW TOKEN", jObj.getString(AUTH_ACCESS_TOKEN));
                        Log.d("NEW EXPIRATION", jObj.getString(AUTH_EXPIRES));
                        Log.d("NEW REFRESH TOKEN", jObj.getString(AUTH_REFRESH_TOKEN));
                        if (onAuthenticatedListener != null) {
                            onAuthenticatedListener.onAuthenticated(jObj.getString(AUTH_ACCESS_TOKEN));
                        }
                    } catch (JSONException e) {
                        //TODO: handle malformed json
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            }
    ) {
        @Override
        public String getBodyContentType() {
            return String.format("application/x-www-form-urlencoded; charset=%s", new Object[]{"utf-8"});
        }

        @Override
        public byte[] getBody() {
            return refreshAuthBody.getBytes(Charset.forName("utf-8"));
        }

    };
    VolleySingleton.getInstance(mContext).addToRequestQueue(authRequest);
}

public interface OnAuthenticatedListener {
    void onAuthenticated(String auth_token);
}

在onResponse我收到了很多数据,也是因为日期和时间与getParams中设置的时间间隔不同,为什么?错误在哪里?如果我删除了getParams方法,我将获得与结果相同的数据。

1 个答案:

答案 0 :(得分:0)

我认为答案可能是您正在使用 JSONObjectRequest 而不是 StringRequest 。 JsonObjectRequest会覆盖getBody()方法,因此getParam()方法永远不会运行。你可以在这里阅读更多相关信息。

Android: Volley HTTP Request custom header

尝试使用StringRequest查看是否有效。