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:com.nxt.zyl.data.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, final Request<?> request)
        throws IOException, AuthFailureError {
    connection.setDoOutput(true);//from   www. ja  v a2  s.c om
    connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());

    if (request instanceof MultiPartRequest) {
        final UploadMultipartEntity multipartEntity = ((MultiPartRequest<?>) request).getMultipartEntity();
        // 
        connection.setFixedLengthStreamingMode((int) multipartEntity.getContentLength());
        multipartEntity.writeTo(connection.getOutputStream());
    } else {
        byte[] body = request.getBody();
        if (body != null) {
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body);
            out.close();
        }
    }
}

From source file:com.binil.pushnotification.ServerUtil.java

/**
 * Issue a POST request to the server.//from w w  w .j  a va2  s .  c  o m
 *
 * @param endpoint POST address.
 * @param params   request parameters.
 * @throws java.io.IOException propagated from POST.
 */
private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException {

    URL url = new URL(endpoint);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate");
    urlConnection.setRequestProperty("Accept", "*/*");

    urlConnection.setDoOutput(true);

    JSONObject json = new JSONObject(params);
    String body = json.toString();
    urlConnection.setFixedLengthStreamingMode(body.length());

    try {
        OutputStream os = urlConnection.getOutputStream();
        os.write(body.getBytes("UTF-8"));
        os.close();

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

    } finally {
        int status = urlConnection.getResponseCode();
        String connectionMsg = urlConnection.getResponseMessage();
        urlConnection.disconnect();

        if (status != HttpURLConnection.HTTP_OK) {
            Log.wtf(TAG, connectionMsg);
            throw new IOException("Post failed with error code " + status);
        }
    }

}

From source file:com.newrelic.agent.Deployments.java

static int recordDeployment(CommandLine cmd, AgentConfig config)/*  37:    */ throws Exception
/*  38:    */ {//from  www .j av a 2 s .  c  o m
    /*  39: 35 */ String appName = config.getApplicationName();
    /*  40: 36 */ if (cmd.hasOption("appname")) {
        /*  41: 37 */ appName = cmd.getOptionValue("appname");
        /*  42:    */ }
    /*  43: 39 */ if (appName == null) {
        /*  44: 40 */ throw new IllegalArgumentException(
                "A deployment must be associated with an application.  Set app_name in newrelic.yml or specify the application name with the -appname switch.");
        /*  45:    */ }
    /*  46: 43 */ System.out.println("Recording a deployment for application " + appName);
    /*  47:    */
    /*  48: 45 */ String uri = "/deployments.xml";
    /*  49: 46 */ String payload = getDeploymentPayload(appName, cmd);
    /*  50: 47 */ String protocol = "http" + (config.isSSL() ? "s" : "");
    /*  51: 48 */ URL url = new URL(protocol, config.getApiHost(), config.getApiPort(), uri);
    /*  52:    */
    /*  53: 50 */ System.out.println(MessageFormat.format("Opening connection to {0}:{1}",
            new Object[] { config.getApiHost(), Integer.toString(config.getApiPort()) }));
    /*  54:    */
    /*  55:    */
    /*  56: 53 */ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    /*  57: 54 */ conn.setRequestProperty("x-license-key", config.getLicenseKey());
    /*  58:    */
    /*  59: 56 */ conn.setRequestMethod("POST");
    /*  60: 57 */ conn.setConnectTimeout(10000);
    /*  61: 58 */ conn.setReadTimeout(10000);
    /*  62: 59 */ conn.setDoOutput(true);
    /*  63: 60 */ conn.setDoInput(true);
    /*  64:    */
    /*  65: 62 */ conn.setRequestProperty("Content-Length", Integer.toString(payload.length()));
    /*  66: 63 */ conn.setFixedLengthStreamingMode(payload.length());
    /*  67: 64 */ conn.getOutputStream().write(payload.getBytes());
    /*  68:    */
    /*  69: 66 */ int responseCode = conn.getResponseCode();
    /*  70: 67 */ if (responseCode < 300)
    /*  71:    */ {
        /*  72: 68 */ System.out.println("Deployment successfully recorded");
        /*  73:    */ }
    /*  74: 69 */ else if (responseCode == 401)
    /*  75:    */ {
        /*  76: 70 */ System.out.println(
                "Unable to notify New Relic of the deployment because of an authorization error.  Check your license key.");
        /*  77: 71 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  78:    */ }
    /*  79:    */ else
    /*  80:    */ {
        /*  81: 73 */ System.out.println("Unable to notify New Relic of the deployment");
        /*  82: 74 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  83:    */ }
    /*  84: 76 */ boolean isError = responseCode >= 300;
    /*  85: 77 */ if ((isError) || (config.isDebugEnabled()))
    /*  86:    */ {
        /*  87: 78 */ System.out.println("Response code: " + responseCode);
        /*  88: 79 */ InputStream inStream = isError ? conn.getErrorStream() : conn.getInputStream();
        /*  89: 81 */ if (inStream != null)
        /*  90:    */ {
            /*  91: 82 */ ByteArrayOutputStream output = new ByteArrayOutputStream();
            /*  92: 83 */ Streams.copy(inStream, output);
            /*  93:    */
            /*  94: 85 */ PrintStream out = isError ? System.err : System.out;
            /*  95:    */
            /*  96: 87 */ out.println(output);
            /*  97:    */ }
        /*  98:    */ }
    /*  99: 90 */ return responseCode;
    /* 100:    */ }

From source file:com.jooketechnologies.network.ServerUtilities.java

static JSONObject post(String endpoint, int action, Map<String, String> params) {
    URL url;/*from  ww w .  j a  v a  2  s.c  o  m*/
    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();
        InputStream is = conn.getInputStream();
        if (status != 200) {
            if (conn != null) {
                conn.disconnect();
            }
        } else {
            JSONObject jsonObject = streamToString(is);
            return jsonObject;
        }
    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;

}

From source file:com.onesignal.OneSignalRestClient.java

private static void makeRequest(String url, String method, JSONObject jsonBody,
        ResponseHandler responseHandler) {
    HttpURLConnection con = null;
    int httpResponse = -1;
    String json = null;//  w w w  .  j a v a 2 s.  com

    try {
        con = (HttpURLConnection) new URL(BASE_URL + url).openConnection();
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setConnectTimeout(TIMEOUT);
        con.setReadTimeout(TIMEOUT);

        if (jsonBody != null)
            con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestMethod(method);

        if (jsonBody != null) {
            String strJsonBody = jsonBody.toString();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody);

            byte[] sendBytes = strJsonBody.getBytes("UTF-8");
            con.setFixedLengthStreamingMode(sendBytes.length);

            OutputStream outputStream = con.getOutputStream();
            outputStream.write(sendBytes);
        }

        httpResponse = con.getResponseCode();

        InputStream inputStream;
        Scanner scanner;
        if (httpResponse == HttpURLConnection.HTTP_OK) {
            inputStream = con.getInputStream();
            scanner = new Scanner(inputStream, "UTF-8");
            json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
            scanner.close();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json);

            if (responseHandler != null)
                responseHandler.onSuccess(json);
        } else {
            inputStream = con.getErrorStream();
            if (inputStream == null)
                inputStream = con.getInputStream();

            if (inputStream != null) {
                scanner = new Scanner(inputStream, "UTF-8");
                json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                scanner.close();
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json);
            } else
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN,
                        method + " HTTP Code: " + httpResponse + " No response body!");

            if (responseHandler != null)
                responseHandler.onFailure(httpResponse, json, null);
        }
    } catch (Throwable t) {
        if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException)
            OneSignal.Log(OneSignal.LOG_LEVEL.INFO,
                    "Could not send last request, device is offline. Throwable: " + t.getClass().getName());
        else
            OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t);

        if (responseHandler != null)
            responseHandler.onFailure(httpResponse, null, t);
    } finally {
        if (con != null)
            con.disconnect();
    }
}

From source file:com.deltadna.android.sdk.net.RequestBody.java

void fill(HttpURLConnection connection) throws IOException {
    connection.setFixedLengthStreamingMode(content.length);
    connection.setRequestProperty("Content-Type", type);

    OutputStream output = null;//  w  ww  .j  a v a2 s. co m
    try {
        output = connection.getOutputStream();
        output.write(content);
    } finally {
        if (output != null) {
            output.close();
        }
    }
}

From source file:rapture.dp.invocable.notification.steps.NotificationStep.java

private int doPost(URL url, byte[] body) throws IOException {
    HttpURLConnection http = (HttpURLConnection) url.openConnection();
    http.setFixedLengthStreamingMode(body.length);
    http.setRequestProperty("Content-Type", MediaType.JSON_UTF_8.toString());
    http.setRequestMethod("POST");
    http.setDoOutput(true);//w w w .  jav a2s.  c o  m
    http.connect();
    try (OutputStream stream = http.getOutputStream()) {
        stream.write(body);
    }
    int response = http.getResponseCode();
    http.disconnect();
    return response;
}

From source file:acc.healthapp.notification.HttpRequest.java

/**
 * Post the request/*w ww.  j  av a  2s .  co m*/
 * @param url where to post to
 * @param requestBody the body of the request
 * @throws IOException
 */
public void doPost(String url, String requestBody) throws IOException {
    Log.i("", "HTTP request. body: " + requestBody);

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(requestBody.getBytes().length);
    conn.setRequestMethod("POST");
    for (int i = 0; i < mHeaders.size(); i++) {
        conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i));
    }
    OutputStream out = null;
    try {
        out = conn.getOutputStream();
        out.write(requestBody.getBytes());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    responseCode = conn.getResponseCode();

    InputStream inputStream = null;
    try {
        if (responseCode == 200) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        responseBody = getString(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    Log.i("", "HTTP response. body: " + responseBody);

    conn.disconnect();
}

From source file:com.tdevelopers.questo.Pushes.HttpRequest.java

/**
 * Post the request/*  w w w .  j  ava 2s  . c om*/
 *
 * @param url         where to post to
 * @param requestBody the body of the request
 * @throws IOException
 */
public void doPost(String url, String requestBody) throws IOException {
    Log.i(LoggingService.LOG_TAG, "HTTP request. body: " + requestBody);
    Log.i(LoggingService.LOG_TAG, "header" + mHeaders.toString());
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(requestBody.getBytes().length);
    conn.setRequestMethod("POST");
    for (int i = 0; i < mHeaders.size(); i++) {
        conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i));
    }
    OutputStream out = null;
    try {
        out = conn.getOutputStream();
        out.write(requestBody.getBytes());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    responseCode = conn.getResponseCode();

    InputStream inputStream = null;
    try {
        if (responseCode == 200) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        responseBody = getString(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    Log.i(LoggingService.LOG_TAG, "HTTP response. body: " + responseBody);

    conn.disconnect();
}

From source file:com.google.android.gcm.demo.logic.HttpRequest.java

/**
 * Post the request/* w w w  . ja v  a  2  s.  c  o m*/
 * @param url where to post to
 * @param requestBody the body of the request
 * @throws IOException
 */
public void doPost(String url, String requestBody) throws IOException {
    Log.i(LoggingService.LOG_TAG, "HTTP request. body: " + requestBody);

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(requestBody.getBytes().length);
    conn.setRequestMethod("POST");
    for (int i = 0; i < mHeaders.size(); i++) {
        conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i));
    }
    OutputStream out = null;
    try {
        out = conn.getOutputStream();
        out.write(requestBody.getBytes());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    responseCode = conn.getResponseCode();

    InputStream inputStream = null;
    try {
        if (responseCode == 200) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        responseBody = getString(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    Log.i(LoggingService.LOG_TAG, "HTTP response. body: " + responseBody);

    conn.disconnect();
}