Jackson error “Illegal character… only regular white space allowed” when parsing JSON

前端 未结 5 2087
刺人心
刺人心 2020-12-17 17:54

I am trying to retrieve JSON data from a URL but get the following error:

Illegal character ((CTRL-CHAR, code 31)):
only regular white space (\\r, \\n,\\t) i         


        
5条回答
  •  被撕碎了的回忆
    2020-12-17 18:26

    I had the same problem. After setting Gzip it was fixed. Please refer my code

    public String sendPostRequest(String req) throws Exception {
    
        // Create connection
        URL urlObject = new URL(mURL);
        HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", Integer.toString(req.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
    
        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(req);
        wr.close();
    
        //Response handling
        InputStream responseBody                = null;
        if (isGzipResponse(connection)) {
            responseBody                = new GZIPInputStream(connection.getInputStream());         
        }else{
            responseBody = connection.getInputStream();
        }
        convertStreamToString(responseBody);
    
        return response.toString();
    
    }
    
    protected boolean isGzipResponse(HttpURLConnection con) {
        String encodingHeader = con.getHeaderField("Content-Encoding");
        return (encodingHeader != null && encodingHeader.toLowerCase().indexOf("gzip") != -1);
    }
    
    public void convertStreamToString(InputStream in) throws Exception {
        if (in != null) {
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int length = 0;
            while ((length = in.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
    
            response = new String(baos.toByteArray());
    
            baos.close();
    
        } else {
            response = null;
        }
    
    }
    

提交回复
热议问题