-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.

Raj
  • 127
  • 2
  • 2
  • 8
  • 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);` – Olavi Mustanoja Dec 02 '14 at 06:46
  • With guava: `Splitter.on("&").withKeyValueSeparator("=").split(yourString);` gives you a `Map` then a `get("access_token")` gives you the wanted value. –  Dec 02 '14 at 06:46

2 Answers2

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.
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
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]);
Secondo
  • 451
  • 4
  • 9