Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
package com.copenhacks2018;
import java.util.*;
* Gson:
* Maven info:
* groupId:
* artifactId: gson
* version: 2.8.1
* Once you have compiled or downloaded gson-2.8.1.jar, assuming you have placed it in the
* same folder as this file (, you can compile and run this program at
* the command line as follows.
* javac -classpath .;gson-2.8.1.jar -encoding UTF-8
* java -cp .;gson-2.8.1.jar GetSentiment
class Document {
public String id, language, text;
public Document(String id, String language, String text){ = id;
this.language = language;
this.text = text;
class Documents {
public List<Document> documents;
public Documents() {
this.documents = new ArrayList<Document>();
public void add(String id, String language, String text) {
this.documents.add (new Document (id, language, text));
public class GetSentiment {
// ***********************************************
// *** Update or verify the following values. ***
// **********************************************
// Replace the accessKey string value with your valid access key.
static String accessKey = "b83bdf9fa7854054b5542ae297ac6d0e";
// Replace or verify the region.
// You must use the same region in your REST API call as you used to obtain your access keys.
// For example, if you obtained your access keys from the westus region, replace
// "westcentralus" in the URI below with "westus".
// NOTE: Free trial access keys are generated in the westcentralus region, so if you are using
// a free trial access key, you should not need to change this region.
static String host = "";
static String path = "/text/analytics/v2.0/sentiment";
public static String GetSentiment (Documents documents) throws Exception {
String text = new Gson().toJson(documents);
byte[] encoded_text = text.getBytes("UTF-8");
URL url = new URL(host+path);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "text/json");
connection.setRequestProperty("Ocp-Apim-Subscription-Key", accessKey);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(encoded_text, 0, encoded_text.length);
StringBuilder response = new StringBuilder ();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
return response.toString();
public static String prettify(String json_text) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(json_text).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.