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:ca.xecure.easychip.CommonUtilities.java

public static void http_post(String endpoint, Map<String, String> params) throws IOException {
    URL url;/*  ww w.  j a  va 2s . 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:Main.java

/**
 * Issue a POST request to the server.//from  ww  w.jav a2s.  co  m
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws java.io.IOException
 *             propagated from POST.
 */
public 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();
    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/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);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:Main.java

/**
 * Issue a POST request to the server./*from w  ww. j  ava  2s.  c om*/
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws IOException
 *             propagated from POST.
 */
public static String post_t(String endpoint, Map<String, Object> params, String contentType)
        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, Object>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, Object> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    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);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:it.unicaradio.android.gcm.GcmServerRpcCall.java

/**
 * @param url//from  w  ww .j  av a  2 s  .  c om
 * @param bytes
 * @return
 * @throws IOException
 * @throws ProtocolException
 */
private static HttpURLConnection setupConnection(URL url, byte[] bytes) throws IOException, ProtocolException {
    HttpURLConnection conn;
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    return conn;
}

From source file:Main.java

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

    URL url;// ww  w .j  av a2 s. c  o  m
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Map.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:org.restcomm.app.utillib.Reporters.WebReporter.RegistrationRequest.java

public static HttpURLConnection POSTConnection(String host, DeviceInfo device, String email, String password,
        boolean share) throws Exception {
    URL url = new URL(host + END_POINT);
    String message = toJSON(device, email, password, share);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);//  w  ww  .  j a  v  a  2 s  . com
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setFixedLengthStreamingMode(message.getBytes().length);

    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

    LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "authorizeDevice", url.toString());

    //open
    conn.connect();

    //setup send
    OutputStream os = new BufferedOutputStream(conn.getOutputStream());
    os.write(message.getBytes());
    //clean up
    os.flush();
    return conn;

}

From source file:com.google.android.gcm.demo.app.ServerUtilities.java

/**
 * Issue a POST request to the server./*from  w  w  w  .j  a  v a  2  s.c o m*/
 *
 * @param endpoint POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
private static void 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);
    }
    JSONObject jsonObj = new JSONObject(params);
    String body = jsonObj.toString();
    Log.v(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");
        // 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:Main.java

/**
 * Issue a POST request to the server./*w  w  w  .  j a v a 2s  . c  om*/
 *
 * @param endpoint POST address.
 * @param params request parameters.
 * @return response
 * @throws IOException propagated from POST.
 */
private static String executePost(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    StringBuffer response = new StringBuffer();
    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 {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(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);

        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response.toString();
}

From source file:edu.tjhsst.ion.gcmFrame.MainActivity.java

public static void notifSetup(String user_token, String gcm_token, Context mContext) {

    Log.i(TAG, user_token + "\n" + gcm_token);
    Log.i(TAG, "Setting up notification support..");
    try {/*from  w ww. j a v a  2s  . c  o  m*/
        URL url = new URL(ION_SETUP_URL);
        Uri.Builder builder = new Uri.Builder().appendQueryParameter("user_token", user_token)
                .appendQueryParameter("gcm_token", gcm_token);
        byte[] query = builder.build().getEncodedQuery().getBytes();
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setFixedLengthStreamingMode(query.length);
        urlConnection.getOutputStream().write(query);
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String resp = in.readLine();
        if (resp.contains("Now registered")) {

            Toast.makeText(mContext,
                    "Your device can now receive notifications from Intranet."
                            + "To change this, hit the right-side user icon and tap Preferences.",
                    Toast.LENGTH_LONG).show();
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
            sharedPreferences.edit().putBoolean(QuickstartPreferences.ION_SETUP, true).apply();
        } else {
            Toast.makeText(mContext, "An error occurred trying to set up notifications: " + resp,
                    Toast.LENGTH_LONG).show();
        }
    } catch (IOException e) {
        Log.e(TAG, "Setting up notifications failed", e);

    }
}

From source file:org.wso2.carbon.device.mgt.mobile.android.impl.fcm.FCMUtil.java

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

    byte[] bytes = getFCMRequest(message, getFCMTokens(devices)).getBytes();
    HttpURLConnection conn;
    try {//from  ww w. j ava  2 s  . c  o m
        conn = (HttpURLConnection) (new URL(FCM_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(FCM_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 FCM request.", ex);
    }

    return result;
}