HTTP响应标头 - 如何从HTTP响应标头java中检索特定值

时间:2016-08-01 11:32:40

标签: java http-headers json-deserialization

在休息服务中传递密钥并检查响应代码 如果响应代码= 200,那么我将收集所有HTTP响应标头

if (responseCode == 200) {
            bufferReader = new BufferedReader(new InputStreamReader((connection.getInputStream())));
     String output;
     StringBuilder builder = new StringBuilder();
     System.out.println("Output from Server .... \n");
     while ((output = bufferReader.readLine()) != null) 
          builder.append(output);
     System.out.println(builder.toString());     
}    

输出

{ "issued_at" : "1470049186841", 
  "scope" : "core",
 "status" : "approved", 
 "api_product_list" : "[prod]", 
 "expires_in" : "1199", 
 "token_type" : "BearerToken",
 "access_token" : "mX1GlCBhipXSeGi7YRBAr0KvS03J",  
 "refresh_token_expires_in" : "0",
 "refresh_count" : "0"}
从输出

我只想选择access_token值

注意:下面是salesforce代码,我想转换成java

 Map<String,String> responseMap= new Map<String,String>())JSON.deserialize(res.getBody(),Map<String,String>.class);
            return responseMap.get("access_token");

更新:下面的gson api代码

Gson gson = new Gson();
            Map<String, Object> map78 = new HashMap<>();
            map78 = (Map<String, Object>) gson.fromJson(output, map.getClass());

但我得到空值

1 个答案:

答案 0 :(得分:0)

在Marcel的帮助下,我正在使用gson获得答案

BufferedReader br = null;
        String output = null;
        Map<String, Object> responseToken = new HashMap<>();
        if (responseCode == 200) {
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            StringBuilder builder = new StringBuilder();
            while ((output = br.readLine()) != null) {
                builder.append(output);               
            }
            Gson gson = new Gson();          
            responseToken = (Map<String, Object>) gson.fromJson(builder.toString(), responseToken.getClass());
            System.out.println("from map" + responseToken);
        }
        System.out.println ("access token Key "+responseToken.get("access_token"));