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.android.nunes.sophiamobile.gsm.GcmSender.java

public static void enviar(String msg, String token) {

    try {/*from  w w w . j  a v a 2s.  c  o  m*/
        // 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", msg.trim());
        // Where to send GCM message.
        if (token != null) {
            jGcmData.put("to", token.trim());
        } 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("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } 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();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.android.dialer.omni.PlaceUtil.java

/**
 * Executes a post request and return a JSON object
 * @param url The API URL//from   w  w w.  j  av a2 s  .com
 * @param data The data to post in POST field
 * @return the JSON object
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject postJsonRequest(String url, String postData) throws IOException, JSONException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");

    if (DEBUG)
        Log.d(TAG, "Posting: " + postData + " to " + url);

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(postData);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    JSONObject json = new JSONObject(response.toString());
    return json;
}

From source file:Main.java

public static void post(String actionUrl, String file) {
    try {//from  w  ww .  j a v  a  2 s . c om
        URL url = new URL(actionUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
        DataOutputStream ds = new DataOutputStream(con.getOutputStream());
        FileInputStream fStream = new FileInputStream(file);
        int bufferSize = 1024; // 1MB
        byte[] buffer = new byte[bufferSize];
        int bufferLength = 0;
        int length;
        while ((length = fStream.read(buffer)) != -1) {
            bufferLength = bufferLength + 1;
            ds.write(buffer, 0, length);
        }
        fStream.close();
        ds.flush();
        InputStream is = con.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        new String(b.toString().getBytes("ISO-8859-1"), "utf-8");
        ds.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.pureinfo.srm.outlay.action.SearchCheckCodeAction.java

/**
 * /* ww w .ja v a2s.c o  m*/
 * @param strUrl
 * @param strPostRequest
 * @return
 */
public static String getPageContent(String strUrl, String strPostRequest) {
    //
    StringBuffer buffer = new StringBuffer();
    System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
    System.setProperty("sun.net.client.defaultReadTimeout", "5000");
    try {
        URL newUrl = new URL(strUrl);
        HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection();
        //POST
        if (strPostRequest.length() > 0) {
            hConnect.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(hConnect.getOutputStream());
            out.write(strPostRequest);
            out.flush();
            out.close();
        }
        //
        BufferedReader rd = new BufferedReader(new InputStreamReader(hConnect.getInputStream()));
        int ch;
        for (int length = 0; (ch = rd.read()) > -1; length++)
            buffer.append((char) ch);
        rd.close();
        hConnect.disconnect();
        return buffer.toString().trim();
    } catch (Exception e) {
        // return ":";
        return null;
    } finally {
        buffer.setLength(0);
    }
}

From source file:Main.java

public static String getToken(String email, String password) throws IOException {
    // Create the post data
    // Requires a field with the email and the password
    StringBuilder builder = new StringBuilder();
    builder.append("Email=").append(email);
    builder.append("&Passwd=").append(password);
    builder.append("&accountType=GOOGLE");
    builder.append("&source=markson.visuals.sitapp");
    builder.append("&service=ac2dm");

    // Setup the Http Post
    byte[] data = builder.toString().getBytes();
    URL url = new URL("https://www.google.com/accounts/ClientLogin");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setUseCaches(false);//from  w  w w . j  a v a2  s. com
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Content-Length", Integer.toString(data.length));

    // Issue the HTTP POST request
    OutputStream output = con.getOutputStream();
    output.write(data);
    output.close();

    // Read the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line = null;
    String auth_key = null;
    while ((line = reader.readLine()) != null) {
        if (line.startsWith("Auth=")) {
            auth_key = line.substring(5);
        }
    }

    // Finally get the authentication token
    // To something useful with it
    return auth_key;
}

From source file:com.shopgun.android.sdk.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 va  2s  .  c o  m
        connection.addRequestProperty("Content-Type", request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}

From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java

/**
 * Writes a JSON body in this connection from the given list.
 *
 * @param connection The connection./*from  w  w w  .j  a v  a2  s.c  o  m*/
 * @param names      The list to write as a JSON object.
 *
 * @throws IOException If an exception occurred while contacting the server.
 */
private static void writeBody(HttpURLConnection connection, List<String> names) throws IOException {
    OutputStream stream = connection.getOutputStream();
    String body = JSONArray.toJSONString(names);
    stream.write(body.getBytes());
    stream.flush();
    stream.close();
}

From source file:ca.xecure.easychip.CommonUtilities.java

public static void http_post(String endpoint, Map<String, String> params) throws IOException {
    URL url;//  www  .jav  a 2  s.co m
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }

    String body = JSONValue.toJSONString(params);
    Log.v(LOG_TAG, "Posting '" + body + "' to " + url);

    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

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

        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.adanac.module.blog.api.HttpApiHelper.java

public static void baiduPush(int remain) {
    String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl();
    if (pushUrl == null) {
        if (logger.isInfoEnabled()) {
            logger.info("all html page has been pushed!");
        }//  w w  w .  j a v  a  2  s  .  co  m
        return;
    }
    if (remain <= 0) {
        if (logger.isInfoEnabled()) {
            logger.info("there has no remain[" + remain + "]!");
        }
        return;
    }
    if (logger.isInfoEnabled()) {
        logger.info("find push url : " + pushUrl);
    }
    String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token;
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(pushUrl.getBytes("UTF-8"));
        outputStream.write("\r\n".getBytes("UTF-8"));
        outputStream.flush();
        int status = connection.getResponseCode();
        if (logger.isInfoEnabled()) {
            logger.info("baidu-push response code : " + status);
        }
        if (status == HttpServletResponse.SC_OK) {
            String response = IOUtil.read(connection.getInputStream());
            if (logger.isInfoEnabled()) {
                logger.info("baidu-push response : " + response);
            }
            JSONObject result = JSONObject.fromObject(response);
            if (result.getInt("success") >= 1) {
                DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl);
            } else {
                logger.warn("push url failed : " + pushUrl);
            }
            baiduPush(result.getInt("remain"));
        } else {
            logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream()));
        }
    } catch (Exception e) {
        logger.error("baidu push failed ...", e);
    }
}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public static String sendPutRequest(String urlString, String payload) throws IOException {
    LOGGER.info("Sending PUT to " + urlString + " with payload " + payload);
    final long start = System.currentTimeMillis();
    final URL url = new URL(urlString);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//from  w ww  . j  a v a 2s.  com
    conn.setRequestMethod("PUT");
    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);
    }

    final long stop = System.currentTimeMillis();

    LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start));

    return sb.toString();
}