0

我能够生成访问令牌并存储它。但我无法使用此访问令牌获取数据。所以任何人都可以建议我如何在标题字段中设置此访问令牌。我正在android中开发应用程序。当我请求配置文件端点时,它一直给我 403 错误。

我设置授权标头的代码如下: con.setRequestProperty("Authorization","Bearer "+accesstoken); 其中 con 是 URLConnection 对象。

除此之外,我还需要为 con 对象设置哪些标头才能成功请求。

任何类型的帮助将不胜感激。提前致谢。

这是获取配置文件数据的类:

 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;
            }


        }

    }
4

2 回答 2

0

好的,我今天花了一些时间查看您的代码。似乎您缺少一些关键的东西来成功地进行 oauth。

  1. 与 platform.lifelog.sonymobile.com/oauth/2/authorize 通信时,您需要弹出对话框之类的内容。这将使用户有机会同意授权。看起来你只是调用 url 来响应并继续前进。您需要先从服务器获取“代码”
  2. 在您开始接收数据之前,您必须从上面获取“代码”并将您的客户端 ID 和密码发送到 platform.lifelog.sonymobile.com/oauth/2/token 以获取您的令牌。获得该令牌后,您就可以开始查询数据了。

如果您使用负责繁重工作的 oAuth 库,实际上可能会更容易。这是我在网上找到的一个,但我相信还有其他的: https ://github.com/wuman/android-oauth-client

于 2015-07-02T00:58:01.957 回答
0

好的抱歉耽搁了,但我相信我有一个答案给你。问题似乎在于您如何设置范围。例如,您有这一行:

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

我认为它自己会找到它,但是在将它发送到服务器之前你也在对其进行编码。现在,如果您只是删除加号,它应该适合您。像这样:

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

如果这对您不起作用,请告诉我!

于 2015-07-16T22:40:13.060 回答