Example usage for java.net HttpURLConnection getOutputStream

List of usage examples for java.net HttpURLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Writes a JSON payload an {@link HttpURLConnection} object
 * /*from   www.j  a v  a  2s  . co m*/
 * @since 0.0.1
 * @version 0.1.0
 * 
 * @param connection The {@link HttpURLConnection} object to write to
 * @param body The JSON payload to write
 * @throws IOException If there is an error closing the stream
 */
private static void writeBody(HttpURLConnection connection, String body) throws IOException {
    try (OutputStream stream = connection.getOutputStream()) {
        stream.write(body.getBytes());
        stream.flush();
    }
}

From source file:GoogleAPI.java

/**
 * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
 * /*from w w w.j  a v  a 2  s . c  o m*/
 * @param url The URL to query for a JSONObject.
 * @param parameters Additional POST parameters
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);

        final PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.write(parameters);
        pw.close();
        uc.getOutputStream().close();

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            if (uc.getInputStream() != null) {
                uc.getInputStream().close();
            }
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
            if (pw != null) {
                pw.close();
            }
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:dk.nsi.minlog.test.utils.TestHelper.java

public static String sendRequest(String url, String action, String docXml, boolean failOnError)
        throws IOException, ServiceException {
    URL u = new URL(url);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setDoOutput(true);//ww  w  . j  a  v a  2  s  . c om
    uc.setDoInput(true);
    uc.setRequestMethod("POST");
    uc.setRequestProperty("SOAPAction", "\"" + action + "\"");
    uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8;");
    OutputStream os = uc.getOutputStream();

    IOUtils.write(docXml, os, "UTF-8");
    os.flush();
    os.close();

    InputStream is;
    if (uc.getResponseCode() != 200) {
        is = uc.getErrorStream();
    } else {
        is = uc.getInputStream();
    }
    String res = IOUtils.toString(is);

    is.close();
    if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) {
        throw new ServiceException(res);
    }
    uc.disconnect();

    return res;
}

From source file:com.baasbox.android.HttpUrlConnectionClient.java

private static void addBody(HttpRequest request, HttpURLConnection connection) throws IOException {
    InputStream in = request.body;
    if (in != null) {
        connection.setDoOutput(true);/*from   w  ww  .ja  va 2s  .com*/
        copyStream(in, connection.getOutputStream());
    }
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static int insertDataPoints(String urlString, List<IncomingDataPoint> points) throws IOException {
    int code = 0;
    Gson gson = new Gson();

    HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString);
    OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream());

    String json = gson.toJson(points);

    wr.write(json);/*www  .ja va2 s  .  c o  m*/
    wr.flush();
    wr.close();

    code = httpConnection.getResponseCode();

    httpConnection.disconnect();

    return code;
}

From source file:Main.java

public static String openUrl(String url, String method, Bundle params) {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }/*from   w w  w .j a v  a 2  s . co m*/
    String response = "";
    try {
        Log.d(LOG_TAG, method + " URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                System.getProperties().getProperty("http.agent") + " RenrenAndroidSDK");
        if (!method.equals("GET")) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }

        response = read(conn.getInputStream());
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        throw new RuntimeException(e.getMessage(), e);
    }
    return response;
}

From source file:es.tid.cep.esperanza.Utils.java

public static boolean DoHTTPPost(String urlStr, String content) {
    try {//from   w  w w .j  ava 2s. c  om
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.debug("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me.getMessage());
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe.getMessage());
        return false;
    }
}

From source file:software.uncharted.util.HTTPUtil.java

public static String post(String urlToRead, String postData) {
    URL url;/*w  w w .ja va 2s . com*/
    HttpURLConnection conn;
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        InputStream is = conn.getInputStream();
        while ((nRead = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        return buffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to read URL: " + urlToRead + " <" + e.getMessage() + ">");
    }
    return null;
}

From source file:com.eTilbudsavis.etasdk.network.impl.HttpURLNetwork.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);//from   w  w w  .ja  va2 s  . co m
        connection.addRequestProperty(HeaderUtils.CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}

From source file:com.wx.kernel.util.HttpKit.java

/**
 * Send POST request/* ww  w.  ja  v a 2  s . co  m*/
 */
public static String post(String url, Map<String, String> queryParas, String data,
        Map<String, String> headers) {
    HttpURLConnection conn = null;
    try {
        conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
        conn.connect();

        OutputStream out = conn.getOutputStream();
        out.write(data.getBytes(CHARSET));
        out.flush();
        out.close();

        return readResponseString(conn);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}