如何仅从HttpEntity Java获取Json内容

时间:2018-09-04 07:03:59

标签: java httpclient httpentity

使用HttpEntity会得到一个很长的文本,该文本与Json一起也带有特殊字符。

我尝试了正则表达式,但由于将近30000个字符而无法正常工作。

有没有办法我只能从HttpEntity获取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;
}

1 个答案:

答案 0 :(得分:0)

尝试添加以下Headers

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