'How to get response in Map in httpClient?
I'm making a request to my server, but the response is given in String, and I need to get data from there, for example, the if response: {"response":{"balance":85976,"adres":"[email protected]"}} and need to get a balance
CODE:
public class test {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// Создать запрос на получение
HttpGet httpGet = new HttpGet("http://localhost:8080/api/bank/my_wallet");
httpGet.setHeader("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwYXNhaGFycHN1a0BnbWFpbC5jb20iLCJyb2xlIjoiVVNFUiIsImlhdCI6MTY1MjUzNzQ3NSwiZXhwIjoxNjUzNTM3NDc1fQ.zYQqgXA0aeZAMm7JGhv4gOQEtks2iyQqGoqOOrdxy5g");
// модель ответа
CloseableHttpResponse response = null;
try {
// Выполнить (отправить) запрос Get от клиента
response = httpClient.execute(httpGet);
// Получить объект ответа из модели ответа
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println(EntityUtils.toString(responseEntity));
}
} catch (ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
// освободить ресурсы
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
'''
Solution 1:[1]
All you need is a JSON parser for the entity after checking the content type header. https://hc.apache.org/httpcomponents-core-4.4.x/current/httpcore/apidocs/org/apache/http/HttpEntity.html#getContentType()
For example you can use JSONObject from org.json to convert string to json. https://developer.android.com/reference/org/json/JSONObject#JSONObject(java.lang.String)
JSONObject o = new JSONObject(EntityUtils.toString(responseEntity));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | inf3rno |
