Subsequent httpClient calls return initial calls results

44 views Asked by At

I have these methods in a class called HttpHelper. Now the initial call validates user credentials and returns true. That is expected. The next call is to register a user. That seems to go fine with no hiccups and is to return the new user ID. Instead of returning the user ID it returns true again. Almost like it is cached and just returning the result from the initial call. Anyone have any thoughts as to why this might occur?

private static CookieStore sCookieStore;

private static String invoke(HttpUriRequest request)
            throws ClientProtocolException, IOException {
        String result = null;
        DefaultHttpClient httpClient = new DefaultHttpClient();

        // restore cookie
        if (sCookieStore != null) {
            httpClient.setCookieStore((org.apache.http.client.CookieStore) sCookieStore);
        }

        //request.addHeader("Host", "localhost");
        HttpResponse response = httpClient.execute(request);

        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
            builder.append(s);
        }
        result = builder.toString();
        Log.d(TAG, "result is ( " + result + " )");

        // store cookie
        sCookieStore = (CookieStore) ((AbstractHttpClient) httpClient).getCookieStore();
        return result;
    }

public static String invokeGet(String action, List<NameValuePair> params) {
        try {
            StringBuilder sb = new StringBuilder(API_URL);
            sb.append(action);
            if (params != null) {
                for (NameValuePair param : params) {
                    sb.append("?");
                    sb.append(param.getName());
                    sb.append("=");
                    sb.append(param.getValue());
                }
            }
            Log.d(TAG, "url is" + sb.toString());
            //HttpGet httpGet = new HttpGet(URLEncoder.encode(sb.toString(), "UTF-8"));
            HttpGet httpGet = new HttpGet(sb.toString());

            return invoke(httpGet);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }

        return null;
    }

    public static String invokeGet(String action) {
        return invokeGet(action, null);
    }

Here are the calls I am making. As specified above the authResult variable would result in a string result of true. The nextResult should hold the user ID value but instead holds the value true like from the initial request:

String authResult = HttpHelper.invokeGet("<url to validate user>");

        if (this.URL.indexOf("register") > -1)      
            String nextResult = HttpHelper.invokeGet(this.URL);
        else
            String nextResult = HttpHelper.invokeGet(this.URL);

UPDATED: added in the sCookieStore variable.

UPDATED 2: adding in the methods that are being called via the API (MVC .NET):

authResult variable would get this result:

public bool Get(String userName, String userPassword)
        {
            Task<IdentityUser> iu = _repo.FindUser(userName, userPassword);

            if (iu != null)
            {
                FormsAuthentication.SetAuthCookie(userName, false);
                return true;
            }

            return false;
        }

nextResult variable should get this result:

[HttpGet]
    [AllowAnonymous]
    public async Task<IHttpActionResult> RegisterUser(String userName, String userPassword, String huh)
    {
        UserModel userModel = new UserModel();
        userModel.ConfirmPassword = userPassword;
        userModel.UserName = userName;
        userModel.Password = userPassword;

        String userID = "";

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        IdentityResult result = await _repo.RegisterUser(userModel);

        IHttpActionResult errorResult = GetErrorResult(result);

        if (errorResult != null)
        {
            return errorResult;
        }
        else
        {
            Task<IdentityUser> iu = _repo.FindUser(userModel.UserName, userModel.Password);

            using (var context = new AuthContext())
            {
                var userStore = new UserStore<IdentityUser>(context);
                var userManager = new UserManager<IdentityUser>(userStore);

                userID = iu.Result.Id;

                result = await userManager.AddToRoleAsync(userID, "Users");

                errorResult = GetErrorResult(result);

                if (errorResult != null)
                {
                    return errorResult;
                }
            }
        }

        return Ok("userID:" + userID);
    }
1

There are 1 answers

7
Matthew On

It looks like authResult is going to fire invokeGet 2 times, giving it the same argument (this.URL). Within invokeGet, the variable sb is going to be this.URL both times the function fires.

This is a bit curious to me:

   // restore cookie
    if (sCookieStore != null) {
        httpClient.setCookieStore((org.apache.http.client.CookieStore) sCookieStore);
    }

then at the end,

// store cookie
    sCookieStore = (CookieStore) ((AbstractHttpClient) httpClient).getCookieStore();

When is sCookieStore defined? It could be that the cookies aren't being handled correctly and you're making two fresh connections. If getting and setting the cookies is the issue, it might be better to get a cookie if it exists at the beginning of invoke, then set the new one at the end.