Mysterious distortion of JSON strings in Tomcat

I am facing an issue with JSON-String distortion when sending it from a JavaFX application to a Tomcat server. Some symbols are being replaced by strange square symbols:

https://example.com/image1.png

The conversion of JSON to pass correctly - verified by printing the JSON-String to the console in the JavaFX app after serialization. However, once transferred to the Tomcat server using DoPost method, the JSON-String gets distorted. I even tried transferring XML, but faced the same distortion.

Upon investigation, I discovered that the String sent by DoPost remains intact if its length is 7782 symbols or less. If one more symbol is added, squares start appearing:

https://example.com/image2.png

Both the JavaFX app and Tomcat server are running on a local machine using IntelliJ IDEA, so there doesn't seem to be a network problem.

Answer №1

Big shoutout to user Nick over at ru.stackoverflow.com:

He pinpointed the exact cause – the length of inputStream. It turns out that GZIP was not providing the correct value for the inputStream length to the Servlet. I made a switch from this block of code: `public String getInputString(HttpServletRequest req) { String receivedString = "";

    int len = req.getContentLength();
    byte[] input = new byte[len];

    try {
        ServletInputStream sin = req.getInputStream();
        int c = 0;
        int count = 0;
        while ((c = sin.read(input, count, (input.length - count))) > 0) {
            count += 1;
        }
        sin.close();
    } catch (IOException e) {

    }

    receivedString = new String(input);

    return receivedString;
}`[PasteBin-1][1]

to this: `public String getInputString(HttpServletRequest req) { String receivedString = "";

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()))) {
        StringBuilder sb = new StringBuilder("");

        while (reader.ready()) {
            sb.append(reader.readLine());
        }

        if (sb.length() > 0) {
            receivedString = sb.toString();
        }

    } catch (IOException e) {

    }

    return receivedString;
}`[PasteBin-2][2]

And lo and behold, everything functioned as it should.

You can find the original question thread in Russian here: answer on ru.stackoverflow.com

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Beginning multiple-threaded stopwatch instances (the commandHolder became filled while executing the doCommandWithoutWaitingForAReponse exception)

I am facing a challenge with a relatively simple concept... Our Dashboard loads multiple portlets, and I need to track the load time for each one. To achieve this, I have created a basic StopWatch class that needs to run concurrently for each portlet while ...

Issue with Selenium Testing: Struggling to choose a date from the calendar options

For some reason, I am facing an issue where I can't seem to select the date value from the calendar list. However, all the other tests are working perfectly fine. import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa ...

A comprehensive guide to leveraging synchronous execution of setTimeout in JavaScript

Can the desired output shown below be obtained using setTimout? If it is possible, please provide your insight: console.log("1st"); setTimeout(() => { console.log("2nd"); },0); console.log("3rd"); The expected output should be: 1st 2nd 3rd ...

Is there a way to update a JSON Array in PHP by replacing the existing data with the new data?

I am working with a JSON file and have encountered an issue when trying to delete an object. Whenever I create a new array and write it back to the original JSON file, the new data ends up overwriting the entire file. I have tried using functions like arr ...

Step-by-step guide on adding a new array to a JSON file within an Android application

In my app's data folder, there is a JSON file that contains information. { "user": [ { "identifier": "1", "name": "xyz", "contact": [ { "contact": "123" }, { "contact": "456" ...

React-Collapsible Compilation Error

Currently, I am working on a project that involves Spring and ReactJS. I am still new to front-end development. One of the tasks I am trying to accomplish is creating a simple accordion using "REACT-COLLAPSIBLE". The code I have written is quite straight ...

Error: The system encountered a surprise character () at the beginning of the input

Having trouble parsing the JSON response from the following link: and no matter what I try, I keep getting this error message. W/System.err: Unexpected character () at position 0. public class MainActivity extends AppCompatActivity { Text ...

Fetching information from JSON file is unsuccessful

Attempting to retrieve data from a JSON source (). The goal is to extract information about each game including goals, location, and teams. However, the current code implementation seems to be ineffective. let url = "http://www.openligadb.de/api/getma ...

methods for removing white spaces from json webservice output in asp.net

Hello everyone! I'm new to the world of JSON and this is my first experience with a webservice. I have successfully created an ASP.NET Webservice that returns JSON data. Everything seems to be working fine, but there is one issue I need help with. Wh ...

Dynamically saving JSON data into a database using PHP

I receive the following JSON data: {"1":["77","77"],"2":["33","55","66"]} In PHP, I decode it as follows: $organize = json_decode($json); To store these values in a database, I iterate over them like this: foreach($organize->{1} as $pos => $div){ ...

Tips for transmitting JSON containing a byte array to a web API or Postman

I am seeking guidance on how to send data to both a Web API Postman for Web API While I can easily make simple GET Requests to my Web API using Postman, I am unsure about how to send a Byte Array. In Postman, I understand that it involves a PUT request. ...

Is it possible to handle an item within a JSON as a string?

Currently, I'm tackling a Java project that involves handling JSON data structured like this: { "objectList" : [{...}, {...}, ...], "metadata" : {...} } My goal is to extract the object list and metadata as JSON strings. In essence, I ...

Winium is experiencing difficulty locating the JavaFX element

When working with a Windows desktop application, I rely on UISpy to pinpoint specific elements. Using the AutomationId of an element, my code typically looks like this: WiniumDriver driver = new WiniumDriver(new URL("http://localhost:9999"), option); driv ...

I have received a JSON multi-line string after entering information in a textarea

I've been working on a small social network project where users can create and share posts. However, I encountered an issue with formatting when storing and displaying the posts. When a user enters text with line breaks in the post creation form, it ...

Encountering a Keyerror while attempting to access a specific element within a JSON data

I have come across this question multiple times, but the JSON I need to access seems to be slightly different. The JSON structure looks like this: { "timestamp": 1589135576, "level": 20, "gender": "Male", "status": {}, "personalstats": {}, "at ...

Retrieving data from JSON arrays based on specific conditions in Java

I have been utilizing Unirest to retrieve all IDs from an endpoint. The array structure is as follows: [ { "date": "2022-04-05", "timeIn": "2022-04-05 07:00:00", "timeOut": " ...

What is the best way to verify and eliminate unnecessary attributes from a JSON request payload in a node.js application?

My goal is to verify the data in the request payload and eliminate any unknown attributes. Example of a request payload: { "firstname":"john", "lastname":"clinton", "age": 32 } Required attributes: firstname and lastname Optional a ...

Extracting key values from JSON using Node.js

Trying to read a json file using nodejs and locating a specific key within the object is my current task: fs.readFile('./output.json', 'utf8', function(err, data) { if (err) throw err; console.log(Object.keys(data)); } ...

Error: Trying to send FormData to ajax results in an Illegal Invocation TypeError being thrown

Successfully sending a file to the server for processing using the code below: var formData = new FormData(); formData.append('file', $('#fileUpload')[0].files[0]); options = JSON.stringify(options); // {"key": "value"} $.ajax({ ...

Tips on Retrieving JsonResult

I'm encountering some difficulty when trying to write this AJAX function. My goal is to retrieve a JsonResult, which appears to be the most logical solution. However, all of the examples I've come across utilize Json() in order to convert the re ...