Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net URLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:com.fluidops.iwb.cms.util.OpenUp.java

public static List<Statement> extract(String text, URI uri) throws IOException {
    List<Statement> res = new ArrayList<Statement>();
    String textEncoded = URLEncoder.encode(text, "UTF-8");

    String send = "format=rdfxml&text=" + textEncoded;

    // service limit is 10000 chars
    if (mode() == Mode.demo)
        send = stripToDemoLimit(send);/* www . j  a va 2  s .  c  om*/

    // GET only works for smaller texts
    // URL url = new URL("http://openup.tso.co.uk/des/enriched-text?text=" + textEncoded + "&format=rdfxml");

    URL url = new URL(getConfig().getOpenUpUrl());
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    IOUtils.write(send, conn.getOutputStream());
    Repository repository = new SailRepository(new MemoryStore());
    try {
        repository.initialize();
        RepositoryConnection con = repository.getConnection();
        con.add(conn.getInputStream(), uri.stringValue(), RDFFormat.RDFXML);
        RepositoryResult<Statement> iter = con.getStatements(null, null, null, false);
        while (iter.hasNext()) {
            Statement s = iter.next();
            res.add(s);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return res;
}

From source file:com.fluidops.iwb.provider.GoogleRefineProvider.java

/**
 * utility to simplify doing POST requests
 * //w w  w . j  a  v  a 2s  .  com
 * @param url         URL to post to
 * @param parameter      map of parameters to post
 * @return            URLConnection is a state where post parameters have been sent
 * @throws IOException
 * 
 * TODO: move to util class
 */
public static URLConnection doPost(URL url, Map<String, String> parameter) throws IOException {
    URLConnection con = url.openConnection();
    con.setDoOutput(true);

    StringBuilder params = new StringBuilder();
    for (Entry<String, String> entry : parameter.entrySet())
        params.append(StringUtil.urlEncode(entry.getKey())).append("=")
                .append(StringUtil.urlEncode(entry.getValue())).append("&");

    // Send data
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write(params.toString());
    wr.flush();
    wr.close();

    return con;
}

From source file:com.linkedin.pinot.tools.admin.command.AbstractBaseAdminCommand.java

public static String sendPostRequest(String urlString, String payload)
        throws UnsupportedEncodingException, IOException, JSONException {
    final URL url = new URL(urlString);
    final URLConnection conn = url.openConnection();

    conn.setDoOutput(true);
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));

    writer.write(payload, 0, payload.length());
    writer.flush();/*from  w  ww  . j a  va  2s.  co  m*/

    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    final StringBuilder sb = new StringBuilder();
    String line = null;

    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    return sb.toString();
}

From source file:PostTest.java

/**
 * Makes a POST request and returns the server response.
 * @param urlString the URL to post to//from w  ww  . j av  a2s . c  o  m
 * @param nameValuePairs a map of name/value pairs to supply in the request.
 * @return the server reply (either from the input stream or the error stream)
 */
public static String doPost(String urlString, Map<String, String> nameValuePairs) throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
        if (first)
            first = false;
        else
            out.print('&');
        String name = pair.getKey();
        String value = pair.getValue();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
        in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
        if (!(connection instanceof HttpURLConnection))
            throw e;
        InputStream err = ((HttpURLConnection) connection).getErrorStream();
        if (err == null)
            throw e;
        in = new Scanner(err);
    }

    while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
    }

    in.close();
    return response.toString();
}

From source file:org.apache.ctakes.dictionary.lookup.ae.UmlsDictionaryLookupAnnotator.java

public static boolean isValidUMLSUser(String umlsaddr, String vendor, String username, String password)
        throws Exception {
    String data = URLEncoder.encode("licenseCode", "UTF-8") + "=" + URLEncoder.encode(vendor, "UTF-8");
    data += "&" + URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
    data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
    URL url = new URL(umlsaddr);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) {
        wr.write(data);/* www  .  ja v  a  2s . c  o  m*/
        wr.flush();
    }
    try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        boolean result = false;
        String line;
        while ((line = rd.readLine()) != null) {
            if (line.trim().length() > 0) {
                result = line.trim().equalsIgnoreCase("<Result>true</Result>") || line.trim()
                        .equalsIgnoreCase("<?xml version='1.0' encoding='UTF-8'?><Result>true</Result>");
            }
        }
        return result;
    }
}

From source file:org.apache.zeppelin.markdown.PegdownWebSequencelPlugin.java

public static String createWebsequenceUrl(String style, String content) {

    style = StringUtils.defaultString(style, "default");

    OutputStreamWriter writer = null;
    BufferedReader reader = null;

    String webSeqUrl = "";

    try {/*from ww w .j  a v a 2 s  .co  m*/
        String query = new StringBuilder().append("style=").append(style).append("&message=")
                .append(URLEncoder.encode(content, "UTF-8")).append("&apiVersion=1").toString();

        URL url = new URL(WEBSEQ_URL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        writer = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
        writer.write(query);
        writer.flush();

        StringBuilder response = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        writer.close();
        reader.close();

        String json = response.toString();

        int start = json.indexOf("?png=");
        int end = json.indexOf("\"", start);

        if (start != -1 && end != -1) {
            webSeqUrl = WEBSEQ_URL + "/" + json.substring(start, end);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to get proper response from websequencediagrams.com", e);
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(reader);
    }

    return webSeqUrl;
}

From source file:org.kootox.episodesmanager.services.WebHelper.java

/**
 *
 * Download a file from the internet/*from   ww w. java 2 s  .  c om*/
 *
 * @param destinationDirectory the directory where the file will be saved
 * @param destinationFileName the name under which the file is saved
 * @param source the url from which to download the file
 */
public static void downloadFile(File destinationDirectory, String destinationFileName, URL source) {

    FileOutputStream out = null;
    InputStream in = null;

    try {
        URLConnection conn = source.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("content-type", "binary/data");
        in = conn.getInputStream();

        File destinationFile = new File(destinationDirectory, destinationFileName);
        out = new FileOutputStream(destinationFile);

        byte[] b = new byte[1024];
        int count;

        while ((count = in.read(b)) >= 0) {
            out.write(b, 0, count);
        }

    } catch (IOException eee) {
        log.error("Could not download file ", eee);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException eee) {
            log.debug("Could not close stream", eee);
        }
    }

}

From source file:com.linkedin.pinot.tools.admin.command.AbstractBaseAdminCommand.java

public static JSONObject postQuery(String query, String brokerBaseApiUrl) throws Exception {
    final JSONObject json = new JSONObject();
    json.put("pql", query);

    final long start = System.currentTimeMillis();
    final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection();
    conn.setDoOutput(true);
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    final String reqStr = json.toString();
    System.out.println("reqStr = " + reqStr);

    writer.write(reqStr, 0, reqStr.length());
    writer.flush();/* ww w .j a v  a2  s. c  o  m*/
    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    final String res = sb.toString();
    System.out.println("res = " + res);
    final JSONObject ret = new JSONObject(res);
    ret.put("totalTime", (stop - start));

    return ret;
}

From source file:org.benjp.listener.ServerBootstrap.java

private static String postServer(String serviceUri, String params) {
    String serviceUrl = getServerBase() + PropertyManager.getProperty(PropertyManager.PROPERTY_CHAT_SERVER_URL)
            + "/" + serviceUri;
    String allParams = "passphrase=" + PropertyManager.getProperty(PropertyManager.PROPERTY_PASSPHRASE) + "&"
            + params;/*from   w w w. j a  v  a 2  s .c  om*/
    String body = "";
    OutputStreamWriter writer = null;
    try {
        URL url = new URL(serviceUrl);
        URLConnection con = url.openConnection();
        con.setDoOutput(true);

        //envoi de la requte
        writer = new OutputStreamWriter(con.getOutputStream());
        writer.write(allParams);
        writer.flush();

        InputStream in = con.getInputStream();
        String encoding = con.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;
        body = IOUtils.toString(in, encoding);
        if ("null".equals(body))
            body = null;

    } catch (MalformedURLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.

    } finally {
        try {
            writer.close();
        } catch (Exception e) {
        }
    }
    return body;
}

From source file:org.exoplatform.chat.listener.ServerBootstrap.java

private static String postServer(String serviceUri, String params) {
    String serviceUrl = getServerBase() + PropertyManager.getProperty(PropertyManager.PROPERTY_CHAT_SERVER_URL)
            + "/" + serviceUri;
    String allParams = "passphrase=" + PropertyManager.getProperty(PropertyManager.PROPERTY_PASSPHRASE) + "&"
            + params;/*from   ww w  .j a  va2s .  co  m*/
    String body = "";
    OutputStreamWriter writer = null;
    try {
        URL url = new URL(serviceUrl);
        URLConnection con = url.openConnection();
        con.setDoOutput(true);

        //envoi de la requte
        writer = new OutputStreamWriter(con.getOutputStream());
        writer.write(allParams);
        writer.flush();

        InputStream in = con.getInputStream();
        String encoding = con.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;
        body = IOUtils.toString(in, encoding);
        if ("null".equals(body))
            body = null;

    } catch (MalformedURLException e) {
        LOG.warning(e.getMessage());
    } catch (IOException e) {
        LOG.warning(e.getMessage());
    } finally {
        try {
            writer.close();
        } catch (Exception e) {
            LOG.warning(e.getMessage());
        }
    }
    return body;
}