3

I have the following String:

oauth_token=safcanhpyuqu96vfhn4w6p9x&**oauth_token_secret=hVhzHVVMHySB**&application_name=Application_Name&login_url=https%3A%2F%2Fapi-user.netflix.com%2Foauth%2Flogin%3Foauth_token%3Dsafcanhpyuqu96vfhn4w6p9x

I am trying to parse out the value for oauth_token_secret. I need everything from the equals sign (=) to the next ampersand sign (&). So I need to parse out: hVhzHVVMHySB

Currently, I have the following code:

Const.OAUTH_TOKEN_SECRET = "oauth_token_secret";

Const.tokenSecret = 
  content.substring(content.indexOf((Const.OAUTH_TOKEN_SECRET + "="))
    + (Const.OAUTH_TOKEN_SECRET + "=").length(), 
      content.length());

This will start at the beginning of the oauth_token_string, but it will not stop at the next ampersand. I am unsure how to specify to stop at the end of the following ampersand. Can anyone help me?

4 Answers 4

8

The indexOf() methods allow you to specify an optional fromIndex. This allows you to find the next ampersand:

int oauth = content.indexOf(Const.OAUTH_TOKEN_SECRET);
if (oauth != -1) {
  int start = oath + Const.OATH_TOKEN_SECRET.length(); // or
  //int start = content.indexOf('=', oath) + 1;
  int end = content.indexOf('&', start);
  String tokenSecret = end == -1 ? content.substring(start) : content.substring(start, end);
}
Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick, thanks for showing me how this can be done!
2
public static Map<String, String> buildQueryMap(String query)  
{  
  String[] params = query.split("&");  
  Map<String, String> map = new HashMap<String, String>();  
  for (String param : params)  
  {
    String[] pair = param.split("=");
    String name = pair[0];  
    String value = pair[1];  
    map.put(name, value);  
  }  
  return map;  
}

// in your code
Map<String, String> queryMap = buildQueryMap("a=1&b=2&c=3....");
String tokenSecret = queryMap.get(Const.OAUTH_TOKEN_SECRET);

1 Comment

+1 this is the most robust, though a malformed input string could give null pointer or array index exceptions.
1

Using String.split gives a much cleaner solution.

static String getValue(String key, String content) {
  String[] tokens = content.split("[=&]");
  for(int i = 0; i < tokens.length - 1; ++i) {
    if(tokens[i].equals(key)) {
      return tokens[i+1];
    }
  }
  return null;
}

Click here for a test drive! ;-)

Comments

0

A much better solution is using the Pattern and corresponding Matcher class.

By using a capturing group you can check and "cut out" the the appropriate substring in one step.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.