0

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":"pasaharpsuk@gmail.com"}} 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();
        }
    }
}

}

'''

Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
  • `HttpClient` provides you with the raw response of the web server. if you need to parse json, there are [many ways](https://stackoverflow.com/q/2591098/4648586) to do it. – Bagus Tesa May 14 '22 at 14:51

1 Answers1

0

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));
inf3rno
  • 24,976
  • 11
  • 115
  • 197