Example usage for java.net URLConnection getOutputStream

List of usage examples for java.net URLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:PostTest.java

/**
 * Makes a POST request and returns the server response.
 * @param urlString the URL to post to/*from  ww  w  .j a  v a2 s .com*/
 * @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.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  w  w w .ja  v a  2s.  c om
        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.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);/*from   www.  j  ava2  s.  c o  m*/
    try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) {
        wr.write(data);
        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: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);/*from ww w  .j ava2  s. c  o  m*/
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));

    writer.write(payload, 0, payload.length());
    writer.flush();

    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:nz.co.lolnet.lolnetachievements.Achievements.Achievements.java

public static void awardPlayerAchievement(String playername, String achievementname)
        throws MalformedURLException, IOException, ParseException {

    JSONObject data = new JSONObject();
    data.put("serverName", Config.SERVER_NAME);
    data.put("serverKey", Config.SERVER_HASH);
    data.put("achievementName", LolnetAchievements.convertAchievementName(achievementname));
    data.put("playerName", playername.toLowerCase());

    if (Config.DEBUG_MODE) {
        System.out.println(data.toJSONString());
    }/*w  ww.  ja  va2s.c  om*/

    URL url = new URL("https://api-lnetachievements.rhcloud.com/api/achievements");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setConnectTimeout(API_TIMEOUT);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data.toJSONString());
    wr.flush();
    wr.close();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String temp = rd.readLine();
    if (Config.DEBUG_MODE) {
        System.out.println(temp);
    }
    //JSONObject object = (JSONObject) new JSONParser().parse(temp);
    //System.out.println("");
    rd.close();
}

From source file:com.krawler.esp.utils.HttpPost.java

public static String GetResponse(String postdata) {
    try {/*from w ww.  j  a  v  a  2  s. c  o  m*/
        String s = URLEncoder.encode(postdata, "UTF-8");
        // URL u = new URL("http://google.com");
        URL u = new URL("http://localhost:7070/service/soap/");
        URLConnection uc = u.openConnection();
        uc.setDoOutput(true);
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);

        DataOutputStream dstream = new DataOutputStream(uc.getOutputStream());

        // The POST line
        dstream.writeBytes(s);
        dstream.close();

        // Read Response
        InputStream in = uc.getInputStream();
        int x;
        while ((x = in.read()) != -1) {
            System.out.write(x);
        }
        in.close();

        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        StringBuffer buf = new StringBuffer();
        String line;
        while ((line = r.readLine()) != null) {
            buf.append(line);
        }
        return buf.toString();
    } catch (Exception e) {
        // throw e;
        return e.toString();
    }
}

From source file:org.geoserver.security.password.URLMasterPasswordProvider.java

static OutputStream output(URL url, File configDir) throws IOException {
    //check for file url
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File f = DataUtilities.urlToFile(url);
        if (!f.isAbsolute()) {
            //make relative to config dir
            f = new File(configDir, f.getPath());
        }/*from  w w  w .ja v a2  s  .  com*/
        return new FileOutputStream(f);
    } else {
        URLConnection cx = url.openConnection();
        cx.setDoOutput(true);
        return cx.getOutputStream();
    }
}

From source file:com.meetingninja.csse.database.BaseDatabaseAdapter.java

protected static int sendPostPayload(URLConnection connection, String payload) throws IOException {
    Log.d(IRequest.POST, "[URL] " + connection.getURL().toString());
    logPrint(payload);/*w  w w  . ja v  a2s  .c o m*/

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    return ((HttpURLConnection) connection).getResponseCode();
}

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  ava 2  s  . com
    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: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);/*  ww w  . jav a2s .c  o  m*/
    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();
    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;
}