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:gov.nasa.arc.geocam.geocam.HttpPost.java

public static int post(String url, JSONObject json, String username, String password) throws IOException {
    HttpURLConnection conn = createConnection(url, username, password);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "application/json");

    byte[] jsonBytes = json.toString().getBytes("UTF-8");

    conn.setRequestProperty("Content-Length", Integer.toString(jsonBytes.length));

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.write(jsonBytes);//from  w w w .j  av a2  s  .  c o m
    out.flush();

    InputStream in = conn.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048);

    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
    }
    out.close();

    int responseCode = 0;
    responseCode = conn.getResponseCode();
    return responseCode;
}

From source file:com.google.api.ads.adwords.awreporting.server.appengine.exporter.ReportExporterAppEngine.java

public static void html2PdfOverNet(InputStream htmlSource, ReportWriter reportWriter) {
    try {//from  w  ww.  jav  a2s  .  com
        URL url = new URL(HTML_2_PDF_SERVER_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/html");
        connection.setRequestProperty("charset", "utf-8");
        connection.setUseCaches(false);

        DataOutputStream send = new DataOutputStream(connection.getOutputStream());
        send.write(IOUtils.toByteArray(htmlSource));
        send.flush();

        // Read from connection
        reportWriter.write(connection.getInputStream());

        send.close();

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *//*  w  w w .  j  a  va2 s . c  om*/
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.github.thorqin.webapi.oauth2.OAuthClient.java

public static AccessToken obtainAccessTokenByCode(String authorityServerUri, String clientId,
        String clientSecret, String code, String redirectUri, boolean useBasicAuthentication)
        throws IOException, OAuthException {
    String rawData = makeObtainAccessTokenByCode(clientId, clientSecret, code, redirectUri,
            useBasicAuthentication);//from ww  w  .  j a  v a2 s .  co m
    String type = "application/x-www-form-urlencoded";
    URL u = new URL(authorityServerUri);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setDoOutput(true);
    if (useBasicAuthentication) {
        String basicAuthentication = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes());
        conn.setRequestProperty("Authorization", "Basic " + basicAuthentication);
    }
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", type);
    conn.setRequestProperty("Content-Length", String.valueOf(rawData.length()));
    try (OutputStream os = conn.getOutputStream()) {
        os.write(rawData.getBytes());
    }
    try (InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is)) {
        AccessTokenResponse token = Serializer.fromJson(reader, AccessTokenResponse.class);
        if (token.error != null) {
            throw new OAuthException(token.error, token.errorDescription, token.errorUri);
        }
        return token;
    }
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static void sendMessageToTopic(String topic, String message) {
    try {//from w  w w . j a va  2s  .c om
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", message);
        // Where to send GCM message.
        String topicName = "/topics/topic_thyN_" + topic.trim();
        if (topic != null) {
            jGcmData.put("to", topicName);
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Sending message: '" + message + "' to " + topicName);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    }
}

From source file:Main.java

public static String executePost(String url, String parameters) throws IOException {

    URL request = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) request.openConnection();
    connection.setDoOutput(true);// w w w. j  av a 2 s .c  o  m
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("User-Agent", "StripeConnectAndroid");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
    connection.setUseCaches(false);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(parameters);
    wr.flush();
    wr.close();

    String response = streamToString(connection.getInputStream());
    connection.disconnect();
    return response;

}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Prepare a <code>POST</code> Http request.
 *///from   www  . ja v a 2 s  . c o m
public static HttpURLConnection newPostRequest(Context context, String uri, Set<String> cookies,
        Map<String, String> params, String charset) throws IOException {
    final StringBuilder query = new StringBuilder();
    if (params != null) {
        for (final Map.Entry<String, String> e : params.entrySet()) {
            if (query.length() != 0) {
                query.append("&");
            }
            query.append(e.getKey()).append("=").append(URLEncoder.encode(e.getValue()));
        }
    }

    final byte[] payload = query.toString().getBytes(charset);

    final HttpURLConnection conn = newRequest(context, uri, cookies);
    conn.setDoOutput(true);
    conn.setFixedLengthStreamingMode(payload.length);
    conn.setRequestProperty("Accept-Charset", charset);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
    conn.setRequestProperty("Referer", uri);

    final OutputStream queryOutput = conn.getOutputStream();
    try {
        queryOutput.write(payload);
    } finally {
        IOUtils.close(queryOutput);
    }

    return conn;
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

public static String postFiles(String url, Map<String, String> vars, Map<String, File> files) {
    try {/* w  ww  .  j ava2s .c o  m*/
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        assembleMultipartFiles(out, vars, files);

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        return "Encoding exception: " + e;
    } catch (IOException e) {
        return "IOException: " + e;
    } catch (IllegalStateException e) {
        return "IllegalState: " + e;
    }
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p />/*from  www  . j a  v a2  s  .co m*/
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url URL to submit the POST request to
 * @param post POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequestWithAuth(final URL url, final String post, final String contentType,
        final String auth) throws IOException {
    Validate.notNull(url);
    Validate.notNull(post);
    Validate.notNull(contentType);
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Authorization", auth);
    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;// ww w.  ja v a 2  s  .com
    URL url = new URL(urlstr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //       connection.setRequestProperty("token",token);
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.connect();

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

    String content = "";
    if (params != null && params.size() > 0) {
        for (int i = 0; i < params.size(); i++) {
            content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8")
                    + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
        }
        out.writeBytes(content.substring(1));
    }

    out.flush();
    out.close();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}