Java lookup lookup

I have the following line:

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 the value for oauth_token_secret. I need everything from the equal sign (=) to the next ampersand (&). So I need to parse: hVhzHVVMHySB

I currently 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());

It will start from the beginning of oauth_token_string, but it will not stop at the next ampersand. I'm not sure how to point to a stop at the end of the next ampersand. Can anybody help me?

+3
source share
4 answers

Methods indexOf()allow you to specify optional fromIndex. This allows you to find the following 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);
}
+8
source
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);
+2
source

String.split .

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

!; -)

+1

It is best to use Pattern and the corresponding Matcher .

Using the capture group, you can check and “cut” the corresponding substring in one step.

0
source

Source: https://habr.com/ru/post/1733474/


All Articles