Example usage for java.net HttpURLConnection setFixedLengthStreamingMode

List of usage examples for java.net HttpURLConnection setFixedLengthStreamingMode

Introduction

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

Prototype

public void setFixedLengthStreamingMode(long contentLength) 

Source Link

Document

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

Usage

From source file:org.wso2.carbon.device.mgt.mobile.android.impl.gcm.GCMUtil.java

public static GCMResult sendWakeUpCall(String message, List<Device> devices) {
    GCMResult result = new GCMResult();

    byte[] bytes = getGCMRequest(message, getGCMTokens(devices)).getBytes();
    HttpURLConnection conn;
    try {//from ww w  .  j  a va 2  s. c o  m
        conn = (HttpURLConnection) (new URL(GCM_ENDPOINT)).openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + getConfigurationProperty(GCM_API_KEY));

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

        int status = conn.getResponseCode();
        result.setStatusCode(status);
        if (status != HTTP_STATUS_CODE_OK) {
            result.setErrorMsg(getString(conn.getErrorStream()));
        } else {
            result.setMsg(getString(conn.getInputStream()));
        }
    } catch (ProtocolException e) {
        log.error("Exception occurred while setting the HTTP protocol.", e);
    } catch (IOException ex) {
        log.error("Exception occurred while sending the GCM request.", ex);
    }

    return result;
}

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

/**
 * Prepare a <code>POST</code> Http request.
 *//*from   w  ww  .  ja va  2  s  .  co  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:com.baasbox.service.push.providers.GCMServer.java

public static void validateApiKey(String apikey)
        throws MalformedURLException, IOException, PushInvalidApiKeyException {
    Message message = new Message.Builder().addData("message", "validateAPIKEY").build();
    Sender sender = new Sender(apikey);

    List<String> deviceid = new ArrayList<String>();
    deviceid.add("ABC");

    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    jsonRequest.put(JSON_REGISTRATION_IDS, deviceid);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }/*from  w ww.  j a  v a2s  .co m*/
    String requestBody = JSONValue.toJSONString(jsonRequest);

    String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    byte[] bytes = requestBody.getBytes();

    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + apikey);
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    int status = conn.getResponseCode();
    if (status != 200) {
        if (status == 401) {
            throw new PushInvalidApiKeyException("Wrong api key");
        }
        if (status == 503) {
            throw new UnknownHostException();
        }
    }

}

From source file:com.arthurpitman.common.HttpUtils.java

/**
 * Connects to an HTTP resource using the post method.
 * @param url the URL to connect to./*from   w  w  w .java 2 s . c  o m*/
 * @param requestProperties optional request properties, <code>null</code> if not required.
 * @param postData the data to post.
 * @return the resulting {@link HttpURLConnection}.
 * @throws IOException
 */
public static HttpURLConnection connectPost(final String url, final RequestProperty[] requestProperties,
        final byte[] postData) throws IOException {
    // setup connection
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod(POST_METHOD);

    // send the post form
    connection.setFixedLengthStreamingMode(postData.length);
    addRequestProperties(connection, requestProperties);
    OutputStream outStream = connection.getOutputStream();
    outStream.write(postData);
    outStream.close();

    return connection;
}

From source file:Main.java

static byte[] httpRequest(String url, byte[] requestBytes, int connectionTimeOutMs, int readTimeOutMs) {
    byte[] bArr = null;
    if (!(url == null || requestBytes == null)) {
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        try {//from   w w  w.j  av a2 s.  c  om
            urlConnection = (HttpURLConnection) new URL(url).openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(connectionTimeOutMs);
            urlConnection.setReadTimeout(readTimeOutMs);
            urlConnection.setFixedLengthStreamingMode(requestBytes.length);
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(requestBytes);
            outputStream.close();
            if (urlConnection.getResponseCode() != 200) {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            } else {
                inputStream = urlConnection.getInputStream();
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[16384];
                while (true) {
                    int chunkSize = inputStream.read(buffer);
                    if (chunkSize < 0) {
                        break;
                    } else if (chunkSize > 0) {
                        result.write(buffer, 0, chunkSize);
                    }
                }
                bArr = result.toByteArray();
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e2) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
        } catch (IOException e3) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e4) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e5) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
    return bArr;
}

From source file:bg.phpgcm2.RegistrationIntentService.java

private static void post(String endpoint, Map<String, String> params) throws IOException {

    URL url;//w  w w .  j  a  v a  2s  . c  om
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        Log.e("URL", "> " + url);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        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:no.ntnu.wifimanager.ServerUtilities.java

/**
 * Issue a POST request to server./* w w w. java  2s . c  o  m*/
 *
 * @param serverUrl POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(serverUrl);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + serverUrl);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    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", contentType);
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        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:edu.dartmouth.cs.dartcard.HttpUtilities.java

private static HttpURLConnection makeGetConnection(URL url, byte[] bytes) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//from   w  ww  . ja va 2s. c  om
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

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

    return conn;
}

From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java

private static HttpURLConnection makePostConnection(URL url, byte[] bytes) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/*  w  ww .j  av a 2 s .  c o  m*/
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    // Add in API key
    String authKey = new String(Base64.encodeBase64((key + ":").getBytes()));
    conn.setRequestProperty("Authorization", "Basic " + authKey);

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

    return conn;
}

From source file:org.frb.sf.frbn.ServerUtilities.java

/**
 * Issue a POST request to the server.//from  ww w  .j a va 2s  .c o  m
 *
 * @param endpoint POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
private static String post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    StringBuffer response = new StringBuffer();
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response.toString();
}