Przykład użycia API synchronicznego

Przetwarzanie pojedynczych tekstów, przekazywanych w wejściowym JSON-ie.


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class demo1 {

    static private final String user = "adrsemailowy@prosze.zmienic";
    static private final String nlprestURL = "http://ws.clarin-pl.eu/nlprest2/base/process";

    public static String lpmnProcess(String lpmn, String text) throws Exception {
        URL url = new URL(nlprestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        String input = "{\"text\":\"" + text.replaceAll("\"", "\\\\\"") + "\",\"lpmn\":\"" + lpmn.replaceAll("\"", "\\\\\"") + "\",\"user\":\"" + user + "\"}";
        System.out.println("Request: " + input);
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes("UTF-8"));
        os.flush();
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }
            conn.disconnect();
            return result.toString("UTF-8");

        } else 
        {   StringBuilder sb = new StringBuilder();   
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            for (int c; (c = in.read()) >= 0;) sb.append((char)c);
            throw new Exception("Failed:  HTTP error code: " + conn.getResponseCode() + " error: " + sb.toString());
        }
    }

    public static void main(String[] args) throws Exception {
        String text = "Ala ma kota. Andrzej poszedł do szpitala i długo nie wracał.";
        String lpmn = "any2txt|wcrft2({\"morfeusz2\":false})|fextor({\"features\": \"mm_stat\"})";
        String result = lpmnProcess(lpmn, text);
        System.out.println(result);
    }
}