0

I am able to generate access token and store it. But I am Unable to get data using this access token. so could anyone suggest me how to set this access token in the header field. I am developing application in android. All time when i request for profile endpoint it gives me 403 error.

my code for setting authorization header is as follow: con.setRequestProperty("Authorization","Bearer "+accesstoken); where con is URLConnection object.

And also apart from this which headers I need to set for con object to make successful request.

Any type of help would be appreciated. Thanks in advance.

Here is tha class for getting profile data:

 public class ProfileRequestActivity extends Activity {
    MyUtility utility=new MyUtility(this);
    String urlString="https://platform.lifelog.sonymobile.com/v1/users/me";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Log.d("pROFILE rEQUESt", "true");
        getProfile();
    }
    public void getProfile()
    {

        RequestPackage pkg=new RequestPackage();
        pkg.setUri(urlString);
        pkg.setMethod("GET");
        HTTPManager manager=new HTTPManager(pkg);
        HttpURLConnection con=manager.doConnection();
        Log.d("Access Token",utility.readPrefernce("access_token") );
        con.setRequestProperty("Accept-Charset" , "utf-8");
        con.setRequestProperty("Authorization", "Bearer "+utility.readPrefernce("access_token"));
        con.setRequestProperty("Accept", "application/json");
        //con.setDoInput(true);
        //con.setDoOutput(true);
        con.setRequestProperty("Accept-Encoding", "gzip");
        //con.setRequestProperty("Content-Encoding", "gzip");
        ExtractProfile task=new ExtractProfile();
        task.execute(con);




    }


    public class ExtractProfile extends AsyncTask<HttpURLConnection, Void, Void>
    {        
        @Override
        protected Void doInBackground(HttpURLConnection... params) 
        {
           int responseCode=0;
           //String data="";
        try {
            responseCode = params[0].getResponseCode();
            Map<String,List<String>> headerMap=params[0].getHeaderFields();
            Log.d("MAP",headerMap.toString());
             Log.d("profile response code",""+responseCode);
             Log.d("Header:",params[0].getRequestProperty("Authorization"));
            //data=params[0].getResponseMessage();
             BufferedReader reader;
            if (responseCode == HttpURLConnection.HTTP_OK)
            reader = new BufferedReader(new InputStreamReader(params[0].getInputStream()));
            else
            reader = new BufferedReader(new InputStreamReader((params[0].getErrorStream())));   
            String line;
            StringBuilder data=new StringBuilder();
            while((line=reader.readLine())!=null)
            {
                data.append(line);
            }
            Log.d("data",data.toString());


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

          // Log.d("Data",data);
            return null;
        }
    }



}


    Here is the helper class:

    public class RequestPackage {

        String uri="";
        String method="GET";
        Map<String,String> params=new HashMap<String, String>();
        public String getUri() {
            return uri;
        }
        public void setUri(String uri) {
            this.uri = uri;
        }
        public String getMethod() {
            return method;
        }
        public void setMethod(String method) {
            this.method = method;
        }
        public Map<String, String> getParams() {
            return params;
        }
        public void setParams(Map<String, String> params) {
            this.params = params;
        }
        public void setParam(String key,String value)
        {
            params.put(key, value);
        }

        public String getEncodedParams()
        {
            StringBuilder sb=new StringBuilder();
            for(String key:params.keySet())
            {
                String value=null;
                try {
                    value = URLEncoder.encode(params.get(key),"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                params.put(key, value);
                if(sb.length()>0)
                {
                    sb.append("&");
                    //sb.append(key+"=");
                }
                sb.append(key+"="+value);
            }

            return sb.toString();
        }
    }


    public class HTTPManager {
        RequestPackage pkg;

        public HTTPManager(RequestPackage p)
        {
            pkg=p;
        }

        public HttpURLConnection doConnection()
        {
            URL url;
            HttpURLConnection con=null;
            BufferedReader reader;
            String uri=pkg.getUri();
            Log.d("URI",uri);
            try {
                if(pkg.getMethod().equals("GET"))
                {
                    if(pkg.getParams().size()!=0)
                    uri+="?"+pkg.getEncodedParams();
                }   
                Log.d("Request Package URI",uri);
                url = new URL(uri);         
                con=(HttpURLConnection) url.openConnection();
                con.setRequestMethod(pkg.getMethod());
                //con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                if(pkg.getMethod().equals("POST"))
                {
                    con.setDoOutput(true);
                    con.setDoInput(true);
                    OutputStreamWriter writer=new OutputStreamWriter(con.getOutputStream());
                //  Log.d("ENCODED PARAMETER",uri+"  "+pkg.getEncodedParams());
                    writer.write(pkg.getEncodedParams());
                    writer.flush();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("OUT CON",con.toString());
            return con;     
        }

        static public String readData(HttpURLConnection con)
        {
    //      Log.d("IN CON",con.toString());
    //          String token = con.getHeaderFields();
    //          return token;


            try {
                //Log.d("Connection",con.toString());
                //Log.d("Response",""+con.getResponseCode());
                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb=new StringBuilder();
                String line;
                while((line=reader.readLine())!=null)
                {
                    sb.append(line);
                }
                return sb.toString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }


        }

    }
  • From what I can tell there should not be a problem with you setting up your request this way. Can you provide more code? I think that will help give me a better idea of what may be wrong. – pg316 Jun 20 '15 at 00:50
  • Thanks Robert for your help. I have edited my post which contains all the related codes. Hope you can help me. I am not able to move forward in my project because of this issue. Please help me. – Harshal Shah Jun 23 '15 at 07:19
  • @Robert..Hello Robert. I have included my code. any help would be appreciated. – Harshal Shah Jun 27 '15 at 04:40

2 Answers2

0

Ok I took some time to look through your code today. It seems that you have some key things missing for you to successfully do oauth.

  1. You will need to popup something like a dialog when communicating with platform.lifelog.sonymobile.com/oauth/2/authorize. This will give the user the chance to agree to the authorization. It looks like you just call the url take a response and move on. You need to get the "code" from the server first
  2. Before you can start receiving data you have to take the "code" from above and send your client id and secret to platform.lifelog.sonymobile.com/oauth/2/token to get your token. Once you get that token then you can start querying for data.

It may actually be easier if you use an oAuth library that takes care of the hard work. Here is one that I found online, but I am sure there are others: https://github.com/wuman/android-oauth-client

pg316
  • 1,380
  • 1
  • 8
  • 7
  • Sir , above code is the part after generating access token. I am doing all of the things you have said here to generate access token. In fact I am able to generate access token and store it in shared preference. But when afterwards I make a profile request for an user, I am getting error 403. Above code is the part of how I make profile request using generated access token. – Harshal Shah Jul 03 '15 at 04:33
  • I am following steps as shown in https://developer.sony.com/develop/services/lifelog-api/ – Harshal Shah Jul 03 '15 at 04:43
  • Sorry for the late reply. So you have more code that is running the full oAuth. From your snippets I can't tell what is missing. Can you make your full oAuth code available for me to take a look at, without your actual credentials of course, so that I can download and compile it. Then maybe I can help to find out what is wrong. – pg316 Jul 08 '15 at 07:46
  • Here is the link where you will find my all codes:https://www.dropbox.com/s/nzrreqntxnn0h1e/caretaker.docx?dl=0 – Harshal Shah Jul 11 '15 at 06:10
  • ok so I started looking through your code today. Is there any chance you can zip your oAuth flow code up in to a zip file so that I can plug in a client id and secret and run it. This would really be helpful because on the surface I don't see what could be wrong. You said you get a token and then I see that you are sending the token with the request which all looks fine. Can you zip up a working project for me to try out? – pg316 Jul 13 '15 at 22:24
  • https://www.dropbox.com/s/p6zqd9oz2j1070k/CareTaker.zip?dl=0 Here is link for my zip file. – Harshal Shah Jul 15 '15 at 06:41
  • ok I just grabbed your code and I am trying it out now. I will let you know as soon as I find something. – pg316 Jul 15 '15 at 20:19
  • Please help me out as soon as possible you can...because I am stuck out on my project because of this.Thank you. – Harshal Shah Jul 16 '15 at 21:20
  • Thank you very very much sir.. I got it. Finally I can step further now. Thank a lot. – Harshal Shah Jul 18 '15 at 06:18
0

Ok sorry for the delay, but I believe that I have an answer for you. The problem seems to be with how you are setting up your scopes. For instance you have this line:

pkg.setParam("scope", MyOauth.SCOPE_PROFILE+"+"+MyOauth.SCOPE_LOCATION+"+"+MyOauth.SCOPE_ACTIVITY);

I think on it's own this would be find, but then you are also encoding this before sending it to the server. For now if you just remove the plus signs it should work for you. Like this:

pkg.setParam("scope", MyOauth.SCOPE_PROFILE+" "+MyOauth.SCOPE_LOCATION+" "+MyOauth.SCOPE_ACTIVITY);

Please let me know if this does not work for you!

pg316
  • 1,380
  • 1
  • 8
  • 7