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.wisdombud.right.client.common.HttpKit.java

/**
 * Send POST request// w w w .  ja v  a 2 s .  c  o  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();

        final OutputStream out = conn.getOutputStream();
        out.write(data != null ? data.getBytes(CHARSET) : null);
        out.flush();
        out.close();

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

From source file:bakuposter.gcm.server.POST2GCMessage.java

public static void post(String apiKey, Content content) {

    try {/*w ww  . j  a  v  a2s.  c  om*/
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);
        conn.setDoOutput(true);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(content.getRegistration_ids().get(0));
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        mapper.writeValue(wr, content);
        wr.flush();
        wr.close();
        int responseCode = conn.getResponseCode();
        System.out.println("responseCode = " + responseCode);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String executePost(String targetURL, String urlParameters) {
    try {/*from  w  w  w . j  a v a 2s . c  om*/
        HttpURLConnection connection = (HttpURLConnection) new URL(targetURL).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        //connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(urlParameters.getBytes());
        } finally {
            if (output != null)
                try {
                    output.flush();
                    output.close();
                } catch (IOException logOrIgnore) {
                }
        }
        InputStream response = connection.getInputStream();
        String contentType = connection.getHeaderField("Content-Type");
        String responseStr = "";
        if (true) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(response));
                for (String line; (line = reader.readLine()) != null;) {
                    //System.out.println(line);
                    responseStr = responseStr + line;
                    Thread.sleep(2);
                }
            } finally {
                if (reader != null)
                    try {
                        reader.close();
                    } catch (IOException logOrIgnore) {
                    }
            }
        } else {
            // It's likely binary content, use InputStream/OutputStream.
            System.out.println("Binary content");
        }
        return responseStr;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:Main.java

public static int sendMessage(String auth_token, String registrationId, String message) throws IOException {

    StringBuilder postDataBuilder = new StringBuilder();
    postDataBuilder.append(PARAM_REGISTRATION_ID).append("=").append(registrationId);
    postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=").append("0");
    postDataBuilder.append("&").append("data.payload").append("=")
            .append(URLEncoder.encode("Lars war hier", UTF8));

    byte[] postData = postDataBuilder.toString().getBytes(UTF8);

    // Hit the dm URL.

    URL url = new URL("https://android.clients.google.com/c2dm/send");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/*ww  w  .j a  v a  2  s .co  m*/
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token);

    OutputStream out = conn.getOutputStream();
    out.write(postData);
    out.close();

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

From source file:Main.java

public static void connectAndSendHttp(ByteArrayOutputStream baos) {
    try {//  w w w .j  a v a2  s  .  co m

        URL url;
        url = new URL("http://10.0.2.2:8080");

        String charset = "UTF-8";

        HttpURLConnection conn;

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = conn.getOutputStream();
        output.write(baos.toByteArray());
        output.close();
        conn.getInputStream();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.cubeisland.engine.core.util.McUUID.java

private static HttpURLConnection postQuery(ArrayNode node, int page) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(MOJANG_API_URL_NAME_UUID + page).openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setUseCaches(false);/*from  w ww  . j  a v  a 2  s . c om*/
    con.setDoInput(true);
    con.setDoOutput(true);
    DataOutputStream writer = new DataOutputStream(con.getOutputStream());
    writer.write(node.toString().getBytes());
    writer.close();
    return con;
}

From source file:ilearnrw.utils.ServerHelperClass.java

public static String sendPost(String link, String urlParameters) throws Exception {
    String url = baseUrl + link;// ww  w.  j a  v a  2 s . c o  m

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api"));

    con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    con.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF8");

    wr.write(urlParameters);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}

From source file:com.appdynamics.common.RESTClient.java

public static void sendPost(String urlString, String input, String apiKey) {
    try {/*from  w  w w. j a v a  2s .c om*/
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        conn.setRequestProperty("Authorization",
                "Basic " + new String(Base64.encodeBase64((apiKey).getBytes())));

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        logger.info("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.info(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:Main.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //from w w w .  j  a v a  2s.c  o  m
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        // use method override
        params.putString("method", method);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }

    return response;
}

From source file:org.droidparts.http.worker.HttpURLConnectionWorker.java

public static void postOrPut(HttpURLConnection conn, String contentType, String data) throws HTTPException {
    conn.setRequestProperty("Accept-Charset", UTF8);
    conn.setRequestProperty("Content-Type", contentType);
    conn.setRequestProperty("Connection", "Keep-Alive");

    OutputStream os = null;/*  www.j  a  v  a  2s. c om*/
    try {
        os = conn.getOutputStream();
        os.write(data.getBytes(UTF8));
    } catch (Exception e) {
        throw new HTTPException(e);
    } finally {
        silentlyClose(os);
    }
}