如何使凌空调用同步

时间:2017-02-01 05:31:25

标签: android web-services oauth android-volley

在我的应用程序中,我使用凌空进行联网。现在后端团队已经对Web服务调用进行了一些更改,这是在每次api调用之前我需要再调用一个服务(oauth服务),该服务将在其JSON响应中提供访问令牌。然后,此访问令牌在我的实际服务(登录服务)调用中用作url中的查询。意味着我需要一个接一个地打两个电话。

在我的代码中实现了这一更改,例如说登录服务: 步骤1)调用提供访问令牌的oauth服务。 步骤2)在网址中使用此访问令牌作为登录服务的查询。

现在问题是呼叫不同步,我在登录呼叫后收到访问令牌,因此收到错误

登录服务电话:

 public void onClickLogin(View v) {
        // Tag used to cancel the request
        String tagJSONobj = "json_obj_req";

        String url;

            if(Constants.RUN_AUTH_API) {

                authAuthentication = new AuthAuthentication(tinyDB, SignInActivity.this);
                authAuthentication.getAuthToken();
                url = https://abc.xyz.com/Services/api/UserValidation/userValidate.do?access_token= + tinyDB.getString(Constants.MY_SHARED_PREF_AUTH_TOKEN);
            }else
            {
                url = Constants.SIGNIN_URL;
            }


            showDialog();

            JSONObject object = new JSONObject();
            try {
                object.put("userName", name);
                object.put("password", password);
                object.put("appType", "MOB APP");

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }


            JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, object,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {

                            hidePDialog();

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();
                    System.out.print("error is" + error.getMessage());
                    error.printStackTrace();
                    Toast.makeText(SignInActivity.this, getResources().getString(R.string.login_service_error_message), Toast.LENGTH_SHORT).show();

                }

            }) ;

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(jsonObjReq, tagJSONobj);
        }
    }

OAuth服务电话:

public class AuthAuthentication {
private static final String TAG = AuthAuthentication.class.getSimpleName();
private TinyDB tinyDB;
private Context context;

public AuthAuthentication(TinyDB tinyDB, Context context){
    this.tinyDB = tinyDB;
    this.context = context;
}

public void getAuthToken() {

    String tag_json_obj = "json_obj_req";
    String url = https://abc.xyz.com/Services/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=admin&password=admin";


    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            url, "",
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {

                    try {
                        Log.d(TAG, " Response" + response.toString());
                        tinyDB.putString(Constants.MY_SHARED_PREF_AUTH_TOKEN, "" + response.getString(AppTags.TAG_AUTH_TOKEN));

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

        @Override
        public void onErrorResponse(VolleyError error) {

            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(context, context.getResources().getString(R.string.unable_to_process), Toast.LENGTH_SHORT).show();
        }
    });

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

}

}

1 个答案:

答案 0 :(得分:1)

首先在登录按钮单击和OnResponse方法调用登录Api

上调用OAuthsevice

OAuth服务电话:

public class AuthAuthentication {
private static final String TAG = AuthAuthentication.class.getSimpleName();
private TinyDB tinyDB;
private Context context;

public AuthAuthentication(TinyDB tinyDB, Context context){
this.tinyDB = tinyDB;
this.context = context;
}

public void getAuthToken() {

String tag_json_obj = "json_obj_req";
String url = https://abc.xyz.com/Services/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=admin&password=admin";


JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
        url, "",
        new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {

                try {
                    Log.d(TAG, " Response" + response.toString());
                    tinyDB.putString(Constants.MY_SHARED_PREF_AUTH_TOKEN, "" + response.getString(AppTags.TAG_AUTH_TOKEN));
                    onClickLogin();/// here to peform login

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

    @Override
    public void onErrorResponse(VolleyError error) {

        VolleyLog.d(TAG, "Error: " + error.getMessage());
        Toast.makeText(context, context.getResources().getString(R.string.unable_to_process), Toast.LENGTH_SHORT).show();
    }
});

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

}

<强>更新

如果OAUTH多次调用,我们需要的是不同API的OAUTH密钥......

  

在实用程序文件夹

中创建此类
public interface VolleyResponse {
   void processFinish(String output);
}
  

只需像这样改变你的类构造函数。

public class AuthAuthentication {
private static final String TAG = AuthAuthentication.class.getSimpleName();
private TinyDB tinyDB;
private Context context;
private VolleyResponse delegate;

public AuthAuthentication(TinyDB tinyDB, Context context,VolleyResponse delegate){
  this.tinyDB = tinyDB;
  this.context = context;
  this.delegate= delegate;
}
 --------
 -------
}
  

在AuthAuthentication类的OnResponse方法

@Override
        public void onResponse(JSONObject response) {

            try {
                Log.d(TAG, " Response" + response.toString());
                tinyDB.putString(Constants.MY_SHARED_PREF_AUTH_TOKEN, "" + response.getString(AppTags.TAG_AUTH_TOKEN));
                //send response of volley 
                delegate.processFinish(tinyDB); //it will broadcast your response

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
  

并根据需要使用它。假设你必须在登录时使用点击

login.setOnClickListerner(new View.OnClickListenr(){
     @Override
     public void onClick(View view){
         AuthAuthentication auth= new AuthAuthentication(tinyDB,mContext,new VolleyResponse() {
                @Override
                public void processFinish(String output) {
                       //output conatins response
                       loginApicall();
                }

             }.getAuthToken(); ///if not work then auth.getAuthToken                  

    }
});