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.screenslicer.core.util.Email.java

public static void sendResults(EmailExport export) {
    if (WebApp.DEV) {
        return;/*from   w ww  .  ja  va2 s  .  c o  m*/
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("key", Config.instance.mandrillKey());
    List<Map<String, String>> to = new ArrayList<Map<String, String>>();
    for (int i = 0; i < export.recipients.length; i++) {
        to.add(CommonUtil.asMap("email", "name", "type", export.recipients[i],
                export.recipients[i].split("@")[0], "to"));
    }
    List<Map<String, String>> attachments = new ArrayList<Map<String, String>>();
    for (Map.Entry<String, byte[]> entry : export.attachments.entrySet()) {
        attachments.add(CommonUtil.asMap("type", "name", "content", new Tika().detect(entry.getValue()),
                entry.getKey(), Base64.encodeBase64String(entry.getValue())));
    }
    params.put("message", CommonUtil.asObjMap("track_clicks", "track_opens", "html", "text", "headers",
            "subject", "from_email", "from_name", "to", "attachments", false, false, "Results attached.",
            "Results attached.", CommonUtil.asMap("Reply-To", Config.instance.mandrillEmail()), export.title,
            Config.instance.mandrillEmail(), Config.instance.mandrillEmail(), to, attachments));
    params.put("async", true);
    HttpURLConnection conn = null;
    String resp = null;
    Log.info("Sending email: " + export.title, false);
    try {
        conn = (HttpURLConnection) new URL("https://mandrillapp.com/api/1.0/messages/send.json")
                .openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("User-Agent", "Mandrill-Curl/1.0");
        String data = CommonUtil.gson.toJson(params, CommonUtil.objectType);
        byte[] bytes = data.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", "" + bytes.length);
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        resp = IOUtils.toString(conn.getInputStream(), "utf-8");
        if (resp.contains("\"rejected\"") || resp.contains("\"invalid\"")) {
            Log.warn("Invalid/rejected email addreses");
        }
    } catch (Exception e) {
        Log.exception(e);
    }
}

From source file:LNISmokeTest.java

/**
 * Implement WebDAV PUT http request.//from   w w  w .  j a  v  a  2 s  .com
 * 
 * This might be simpler with a real HTTP client library, but
 * java.net.HttpURLConnection is part of the standard SDK and it
 * demonstrates the concepts.
 * 
 * @param lni the lni
 * @param collHandle the coll handle
 * @param packager the packager
 * @param source the source
 * @param endpoint the endpoint
 * 
 * @throws RemoteException the remote exception
 * @throws ProtocolException the protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 */
private static void doPut(LNISoapServlet lni, String collHandle, String packager, String source,
        String endpoint)
        throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException {
    // assemble URL from chopped endpoint-URL and relative URI
    String collURI = doLookup(lni, collHandle, null);
    URL url = LNIClientUtils.makeDAVURL(endpoint, collURI, packager);
    System.err.println("DEBUG: PUT file=" + source + " to URL=" + url.toString());

    // connect with PUT method, then copy file over.
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    conn.setDoOutput(true);
    fixBasicAuth(url, conn);
    conn.connect();

    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(source);
        out = conn.getOutputStream();
        copyStream(in, out);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                log.error("Unable to close input stream", e);
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                log.error("Unable to close output stream", e);
            }
        }
    }

    int status = conn.getResponseCode();
    if (status < 200 || status >= 300) {
        die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage());
    }

    // diagnostics, and get resulting new item's location if avail.
    System.err.println("DEBUG: sent " + source);
    System.err.println(
            "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage());
    String loc = conn.getHeaderField("Location");
    System.err.println("RESULT: Location=" + ((loc == null) ? "NULL!" : loc));
}

From source file:bluevia.SendSMS.java

public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) {
    try {//from   w  w  w  .j a va 2s .c  o m

        Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount");
        if (blueviaAccount != null) {
            String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key");
            String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret");
            String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key");
            String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret);
            consumer.setMessageSigner(new HmacSha1MessageSigner());
            consumer.setTokenWithSecret(access_key, access_secret);

            URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1");
            HttpURLConnection request = (HttpURLConnection) apiURI.openConnection();

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

            consumer.sign(request);
            request.connect();

            String smsTemplate = "{\"smsText\": {\n  \"address\": {\"phoneNumber\": \"%s\"},\n  \"message\": \"%s\",\n  \"originAddress\": {\"alias\": \"%s\"},\n}}";
            String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key);

            OutputStream os = request.getOutputStream();
            os.write(smsMsg.getBytes());
            os.flush();

            int rc = request.getResponseCode();

            if (rc == HttpURLConnection.HTTP_CREATED)
                log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message));
            else
                log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage()));
        } else
            log.warning("BlueVia Account seems to be not configured!");

    } catch (Exception e) {
        log.severe(String.format("Exception sending SMS: %s", e.getMessage()));
    }
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry,
        String accessToken) throws IOException, UnsupportedRequestVerbException {

    if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) {
        throw new UnsupportedRequestVerbException();
    }//www .j  a  v a  2  s.co m
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request;

        switch (verb) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        default:
            throw new RuntimeException("RequestVerb not implemented: " + verb);
        }

        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));

        request.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, json, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String url = BASE_URL + method;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());
    conn.addRequestProperty("Content-Type", "application/json");

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(json.toString());
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, json, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:br.gov.jfrj.siga.base.ConexaoHTTP.java

public static String get(String URL, HashMap<String, String> header, Integer timeout, String payload)
        throws AplicacaoException {

    try {/*from  ww  w. j  a  va  2 s  . c  o  m*/

        HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();

        if (timeout != null) {
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
        }

        //conn.setInstanceFollowRedirects(true);

        if (header != null) {
            for (String s : header.keySet()) {
                conn.setRequestProperty(s, header.get(s));
            }
        }

        System.setProperty("http.keepAlive", "false");

        if (payload != null) {
            byte ab[] = payload.getBytes("UTF-8");
            conn.setRequestMethod("POST");
            // Send post request
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(ab);
            os.flush();
            os.close();
        }

        //StringWriter writer = new StringWriter();
        //IOUtils.copy(conn.getInputStream(), writer, "UTF-8");
        //return writer.toString();
        return IOUtils.toString(conn.getInputStream(), "UTF-8");

    } catch (IOException ioe) {
        throw new AplicacaoException("No foi possvel abrir conexo", 1, ioe);
    }

}

From source file:dlauncher.authorization.DefaultCredentialsManager.java

private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors)
        throws ProtocolException, IOException, AuthorizationException {
    JSONObject obj = null;/*w  ww  .  j a  va  2 s .co  m*/
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(15 * 1000);
        con.setReadTimeout(15 * 1000);
        con.connect();
        try (OutputStream out = con.getOutputStream()) {
            out.write(post.toString().getBytes(Charset.forName("UTF-8")));
        }
        con.getResponseCode();
        InputStream instr;
        instr = con.getErrorStream();
        if (instr == null) {
            instr = con.getInputStream();
        }
        byte[] data = new byte[1024];
        int length;
        try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) {
            try (InputStream in = new BufferedInputStream(instr)) {
                while ((length = in.read(data)) >= 0) {
                    bytes.write(data, 0, length);
                }
            }
            byte[] rawBytes = bytes.toByteArray();
            if (rawBytes.length != 0) {
                obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8")));
            } else {
                obj = new JSONObject();
            }
            if (!ignoreErrors && obj.has("error")) {
                String error = obj.getString("error");
                String errorMessage = obj.getString("errorMessage");
                String cause = obj.optString("cause", null);
                if ("ForbiddenOperationException".equals(error)) {
                    if ("UserMigratedException".equals(cause)) {
                        throw new UserMigratedException(errorMessage);
                    }
                    throw new ForbiddenOperationException(errorMessage);
                }
                throw new AuthorizationException(
                        error + (cause != null ? "." + cause : "") + ": " + errorMessage);
            }
            return obj;
        }
    } catch (JSONException ex) {
        throw new InvalidResponseException(ex, obj);
    }
}

From source file:com.codelanx.codelanxlib.logging.Debugger.java

/**
 * Sends a JSON payload to a URL specified by the string parameter
 * /*w  ww  .  java  2s . com*/
 * @since 0.1.0
 * @version 0.1.0
 * 
 * @param url The URL to report to
 * @param payload The JSON payload to send via POST
 * @throws IOException If the sending failed
 */
private static void send(String url, JSONObject payload) throws IOException {
    URL loc = new URL(url);
    HttpURLConnection http = (HttpURLConnection) loc.openConnection();
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type", "application/json");
    http.setUseCaches(false);
    http.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) {
        wr.writeBytes(payload.toJSONString());
        wr.flush();
    }
}

From source file:brainleg.app.util.AppWeb.java

/**
 * Copied from ITNProxy//  w  w w  .  j  a v a2 s  .  co  m
 */
private static HttpURLConnection doPost(String url, byte[] bytes) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url);

    connection.setReadTimeout(60 * 1000);
    connection.setConnectTimeout(10 * 1000);
    connection.setRequestMethod(HTTP_POST);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING));
    connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length));

    OutputStream out = new BufferedOutputStream(connection.getOutputStream());
    try {
        out.write(bytes);
        out.flush();
    } finally {
        out.close();
    }

    return connection;
}

From source file:com.iStudy.Study.Renren.Util.java

private static HttpURLConnection openConn(String url, String method, Bundle params) {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }//from  www  .  j av a2 s  .  c  o  m
    try {
        Log.d(LOG_TAG, method + " URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent", USER_AGENT_SDK);
        if (!method.equals("GET")) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }
        return conn;
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java

/**
 * Creates a CouchDB view//  w w w  .  j  a  v  a2s  .c  o  m
 */
public static void makeView(String user, String pw, String url, String viewDef) throws SQLException {
    try {
        URL u = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();
        uc.setDoOutput(true);
        if (user != null && user.length() > 0) {
            uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw));
        }
        uc.setRequestProperty("Content-Type", "application/json");
        uc.setRequestMethod("PUT");
        OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
        wr.write(viewDef);
        wr.close();

        String s = readStringFromConnection(uc);
    } catch (MalformedURLException e) {
        throw new SQLException("Bad URL.");
    } catch (IOException e) {
        throw new SQLException(e.getMessage());
    }
}