从java输出中提取字符串参数值

时间:2014-12-02 06:41:11

标签: java string jsp http servlets

您好我从java代码获得以下输出:

access_token=CAAW2msiMWaQBAJSLGF1YFU3rJzIzZCFKB3ZAi9UaZCTwOU52s9EEuXXnyV0NBdZApNphWWHGCDP9iCVeI7qliXRCc43IERm5oqBeDplk3fZCLpZBEAwRY2NjKm4o3e4LlCiiUjPLdDNophNOxczJ9fMb2cZCAqILbh2cDnID1i4QZBkKGwGTLuikcz6ptt8ZCl4WifaGtFl5O6fgnbIbgM89f&expires=5181699

如何只检索access_token的值?我的代码如下:

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

感谢你。

2 个答案:

答案 0 :(得分:1)

首先,在&符号&上分割线。然后将每个键和值拆分为等于=。搜索"access_token"并显示(或使用)它。像,

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

答案 1 :(得分:0)

您可以使用string

的split()方法来完成此操作

试试这个。

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

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

输出将是

access_token=CAAW2msiMWaQBAJSLGF1YFU3rJzIzZCFKB3ZAi9UaZCTwOU52s9EEuXXnyV0NBdZApNphWWHGCDP9iCVeI7qliXRCc43IERm5oqBeDplk3fZCLpZBEAwRY2NjKm4o3e4LlCiiUjPLdDNophNOxczJ9fMb2cZCAqILbh2cDnID1i4QZBkKGwGTLuikcz6ptt8ZCl4WifaGtFl5O6fgnbIbgM89f

然后获取access_token的值,试试这个,

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

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