我正在向我的服务器发出请求,但响应以字符串形式给出,我需要从那里获取数据,例如 if 响应:{"response":{"balance":85976,"adres": "pasaharpsuk@gmail.com"}} 并且需要平衡
代码:
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();
}
}
}
}
'''
回答1
在检查内容类型标头后,您只需要一个实体的 JSON 解析器。 https://hc.apache.org/httpcomponents-core-4.4.x/current/httpcore/apidocs/org/apache/http/HttpEntity.html#getContentType()
例如,您可以使用 org.json 中的 JSONObject 将字符串转换为 json。 https://developer.android.com/reference/org/json/JSONObject#JSONObject(java.lang.String)
JSONObject o = new JSONObject(EntityUtils.toString(responseEntity));