Adam Soffer
Adam Soffer

Reputation: 1674

How to Post JSON string in Java

I'm trying to post a large JSON string containing tweets. Some of these tweets contain double quotes and lots of special characters. Do I need to encode the JSON string? My code works if there are no special characters or double quotes in the tweets, otherwise I don't get a response.

String jsonString = "{'data': [";

for (Tweet tweet : tweets) {
    jsonString +="{'text': '" + tweet.getText() + "'},";
} 
jsonString += "]}";

public void analyseTweets(String jsonString){
        try {
            // Send data
            URL url = new URL("http://twittersentiment.appspot.com/api/bulkClassifyJson");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(jsonString);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception e) {
            System.out.print("Error dude!: " + e);
        }
    }

Upvotes: 0

Views: 1326

Answers (2)

user784540
user784540

Reputation:

  1. I would recommend to use Google GSON to compose JSON you want to POST.

  2. If you are composing string from parts, I recommend to use StringBuilder or StringBuffer classes, instead of + operators.

  3. Use HttpURLConnection instead of UrlConnection and call conn.setRequestMethod("POST"); before making the request. It is required because by default, if you don't set it directly, your request is going to be a GET request, not a POST one.

  4. URLEncode your data before sending it to the server.

Upvotes: 0

matsev
matsev

Reputation: 33789

Why don't you use an external library such as google-gson to handle the JSON encoding for you?

From the project description:

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Upvotes: 1

Related Questions