-3

Hi I am getting the following output from java code:

access_token=CAAW2msiMWaQBAJSLGF1YFU3rJzIzZCFKB3ZAi9UaZCTwOU52s9EEuXXnyV0NBdZApNphWWHGCDP9iCVeI7qliXRCc43IERm5oqBeDplk3fZCLpZBEAwRY2NjKm4o3e4LlCiiUjPLdDNophNOxczJ9fMb2cZCAqILbh2cDnID1i4QZBkKGwGTLuikcz6ptt8ZCl4WifaGtFl5O6fgnbIbgM89f&expires=5181699

How do I retrieve only the value of access_token? my code is below:

 String line;
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));

        while ((line = reader.readLine()) != null) 
        {
            buffer.append(line);
        }

        reader.close();
        conn.disconnect();
       String response1= buffer.toString();

Thank YOu.

2
  • Well I'm sure there's a lot more sophisticated methods, but an impatient way would be to just do buffer.toString().substring(13, 13 + length-of-token); Commented Dec 2, 2014 at 6:46
  • With guava: Splitter.on("&").withKeyValueSeparator("=").split(yourString); gives you a Map then a get("access_token") gives you the wanted value. Commented Dec 2, 2014 at 6:46

2 Answers 2

1

First, split the line on ampersand &. Then split each key and value on equals =. Search for "access_token" and display (or use) it. Like,

String[] tokens = line.split("&");
for (String token : tokens) {
    String[] kv = token.split("=");
    String key = kv[0];
    String value = kv[1];
    if (key.equalsIgnoreCase("access_token")) {
        System.out.println(value);
        break; // <-- stop because we found it.
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can do this by using split() method of string

Try this.

String [] response = response1.split("&");

System.out.println("My Token : " + response[0]);

the output will be

access_token=CAAW2msiMWaQBAJSLGF1YFU3rJzIzZCFKB3ZAi9UaZCTwOU52s9EEuXXnyV0NBdZApNphWWHGCDP9iCVeI7qliXRCc43IERm5oqBeDplk3fZCLpZBEAwRY2NjKm4o3e4LlCiiUjPLdDNophNOxczJ9fMb2cZCAqILbh2cDnID1i4QZBkKGwGTLuikcz6ptt8ZCl4WifaGtFl5O6fgnbIbgM89f

then to get the value of access_token try this,

  String [] tokenValue = response[0].split("=");

  System.out.println("My Token Value : " + tokenValue[1]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.