英文:
how to get JSON value from HTTP response?
问题
以下是翻译好的部分:
"我想从HTTP请求中检索JSON文件的值。不幸的是,我不知道如何继续。
我正在使用GET方法:
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(new URI("http://localhost:3333/command/core/get-csrf-token"));
HttpEntity entity = client.execute(get).getEntity();
我确实获得了预期的文件,因为我尝试了:
return EntityUtils.toString(entity);
并获得输出:{"token":"myToken"}
"
英文:
I would like to retrieve the value of a JSON file from an HTTP request. Unfortunately, I do not know how to proceed.
I am using the GET method:
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(new URI("http://localhost:3333/command/core/get-csrf-token"));
HttpEntity entity = client.execute(get).getEntity();
I do get the expected file as I tried:
return EntityUtils.toString(entity);
and get as output: {"token":"myToken"}
答案1
得分: 2
你可以将JSON字符串转换为JSONObject
(来自org.json),然后使用getString()
方法获取令牌。
JSONObject result = new JSONObject(EntityUtils.toString(entity));
String token = result.getString("token");
参考链接:http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
英文:
You can convert JSON string into JSONObject
( from org.json) and then get then token using getString()
method
JSONObject result = new JSONObject(EntityUtils.toString(entity));
String token = result.getString("token");
Reference: http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
答案2
得分: 0
试试
JSONObject jsonObject = new JSONObject(EntityUtils.toString(entity));
String token = jsonObject.getString("token");
英文:
try
JSONObject jsonObject = new JSONObject(EntityUtils.toString(entity));
String token = jsonObject.getString("token");
答案3
得分: -1
你可以简单地使用正则表达式(不需要额外的库)。
public static void main(String[] args){
String json = "{\"token\":\"myToken\"}";
System.out.println(extractToken(json));
}
public static String extractToken(String json){
String regexToken = "(?:.*\"token\"\\s*:\\s*\")(?<token>.*?)(?:\".*)";
Pattern patternToken = Pattern.compile(regexToken, Pattern.DOTALL);
Matcher matcherToken = patternToken.matcher(json);
if(matcherToken.matches()){
return matcherToken.group("token");
}else{
return "token_not_found";
}
}
这将在具有多个字段的 JSON 上工作。唯一的条件是整个 JSON 中只能有一个 token
字段。
英文:
You can simply use regex(don't need additional libs).
public static void main(String[] args){
String json = "{\"token\":\"myToken\"}";
System.out.println(extractToken(json));
}
public static String extractToken(String json){
String regexToken = "(?:.*\\\"token\\\"\\s*:\\s*\\\")(?<token>.*?)(?:\\\".*)";
Pattern patternToken = Pattern.compile(regexToken, Pattern.DOTALL);
Matcher matcherToken = patternToken.matcher(json);
if(matcherToken.matches()){
return matcherToken.group("token");
}else{
return "token_not_found";
}
}
This will work even on a json with multiple fields. The only condition is to be only one token
field in the entire json.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论