1
votes

Using Postman I am able to successfully connect to my login server and receive an access token.

I would like to replicate this call within my CN1 code

This is my postman script:

cURL

curl --location --request POST 'https://myloginserver.com/accounts/login' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'username=myusername' \
--data-urlencode 'password=mypassword'

Java

Unirest.setTimeouts(0, 0);
HttpResponse<String> response = Unirest.post("https://myloginserver/accounts/login")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .field("username", "myusername")
  .field("password", "mypassword")
  .asString();

And this is my CN1 code

        ConnectionRequest getTokenConnReq = null;
        try {
            getTokenConnReq = new ConnectionRequest("https://myloginserver.com/accounts/login");
            getTokenConnReq.setPost(true);
            getTokenConnReq.addRequestHeader("Content-Type","application/x-www-form-urlencoded");
            getTokenConnReq.setHttpMethod("POST");
            getTokenConnReq.setRequestBody("username=myusername&password=mypassword");
            getTokenConnReq.setFailSilently(true);
            getTokenConnReq.setCookiesEnabled(false);
            NetworkManager.getInstance().addToQueueAndWait(getTokenConnReq);
            result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(getTokenConnReq.getResponseData()), DocumentInfo.ENCODING_UTF8));
            return result;
        } catch (Exception err22) {
            System.err.println(err22);
            return null;
        }

Unfortunately my responses vary from the 300's to the 400's depending on how I tweak the code. Please advise how I get this working in CN1?

(I think that it may have something to do with Cookies as I do see Postman adding cookies to the call in the background)

Any help will be appreciated.

Thanks

1

1 Answers

1
votes

I would suggest using the Rest API which is much easier to use for these sort of calls:

Rest.post("https://myloginserver.com/accounts/login")
    .contentType("application/x-www-form-urlencoded")
    .queryParam("username", username)
    .queryParam("password", password)
    .fetchAsJsonMap(result -> {
         Map parsedJson = result.getResponseData();
         // key/value pairs from the resulting JSON
    });