如何仅从 HttpEntity Java 获取 Json 内容



使用HttpEntity,我得到了一个很长的文本,其中包含特殊字符以及Json。

我尝试了正则表达式,但它不起作用,因为它几乎有 30000 个字符。

有没有办法我只能从 Http实体获取 Json 数据。甚至字符串拆分也不起作用,因为它有很多特殊字符。

public JSONObject sendGet(String URL, String userName, String password) throws Exception {
getRequest = new HttpGet(URL);
getRequest.addHeader("User-Agent", USER_AGENT);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
provider.setCredentials(AuthScope.ANY, credentials);
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
outputFile = new File(directoryPath + "/target/response.txt");
fos = new FileOutputStream(outputFile);
headers = response.getAllHeaders();
bw = new BufferedWriter(new OutputStreamWriter(fos));
for (Header header: headers) {
bw.write(header.getName() + ": " + header.getValue() + "n");
}
bw.write(response.getEntity());
bw.write("Response Code : " + response.getStatusLine());
String content = EntityUtils.toString(entity); //When i print content it has string other than json as well
JSONObject obj = new JSONObject(content); //Here i receive A JSONObject text must begin with '{' at 1 [character 2 line 1]
JSONArray keys = obj.names();
Object test = JSON.parse(content);
jsonFiles = new File(directoryPath + "/JsonFiles/test.json");
fos = new FileOutputStream(jsonFiles);
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(content);
bw.close();
return obj;
}

尝试添加以下Headers

getRequest.addHeader("Accept", "application/json");
getRequest.addHeader("Content-Type", "application/json");
getRequest.addHeader("Accept-Charset", "utf-8");

相关内容

  • 没有找到相关文章

最新更新