簡體   English   中英

如何僅從HttpEntity Java獲取Json內容

[英]How to get only Json content from HttpEntity Java

使用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;
}

嘗試添加以下Headers

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM