Java Code Examples for java.net.httpurlconnection#setFixedLengthStreamingMode()

The following examples show how to use java.net.httpurlconnection#setFixedLengthStreamingMode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 8 votes vote down vote up
/**
 * Generates a web request to abort a copy operation.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param blobOptions
 *            A {@link BlobRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@link CloudBlobClient}.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @param accessCondition
 *            The access condition to apply to the request. Only lease conditions are supported for this operation.
 * @param copyId
 *            A <code>String</code> object that identifying the copy operation.
 * @return a HttpURLConnection configured for the operation.
 * @throws StorageException
 *             an exception representing any error which occurred during the operation.
 * @throws IllegalArgumentException
 * @throws IOException
 * @throws URISyntaxException
 */
public static HttpURLConnection abortCopy(final URI uri, final BlobRequestOptions blobOptions,
        final OperationContext opContext, final AccessCondition accessCondition, final String copyId)
        throws StorageException, IOException, URISyntaxException {

    final UriQueryBuilder builder = new UriQueryBuilder();

    builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.COPY);
    builder.add(Constants.QueryConstants.COPY_ID, copyId);

    final HttpURLConnection request = BaseRequest.createURLConnection(uri, blobOptions, builder, opContext);

    request.setFixedLengthStreamingMode(0);
    request.setDoOutput(true);
    request.setRequestMethod(Constants.HTTP_PUT);

    request.setRequestProperty(Constants.HeaderConstants.COPY_ACTION_HEADER,
            Constants.HeaderConstants.COPY_ACTION_ABORT);

    if (accessCondition != null) {
        accessCondition.applyLeaseConditionToRequest(request);
    }

    return request;
}
 
Example 2
Source File: GitHubClient.java    From 920-text-editor-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Send parameters to output stream of request
 *
 * @param request
 * @param params
 * @throws IOException
 */
protected void sendParams(HttpURLConnection request, Object params)
        throws IOException {
    request.setDoOutput(true);
    if (params != null) {
        request.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON
                + "; charset=" + CHARSET_UTF8); //$NON-NLS-1$
        byte[] data = toJson(params).getBytes(CHARSET_UTF8);
        request.setFixedLengthStreamingMode(data.length);
        BufferedOutputStream output = new BufferedOutputStream(
                request.getOutputStream(), bufferSize);
        try {
            output.write(data);
            output.flush();
        } finally {
            try {
                output.close();
            } catch (IOException ignored) {
                // Ignored
            }
        }
    } else {
        request.setFixedLengthStreamingMode(0);
        request.setRequestProperty("Content-Length", "0");
    }
}
 
Example 3
Source File: HasteUpload.java    From VanillaFix with MIT License 6 votes vote down vote up
public static String uploadToHaste(String baseUrl, String extension, String str) throws IOException {
    byte[] bytes = str.getBytes(StandardCharsets.UTF_8);

    URL uploadURL = new URL(baseUrl + "/documents");
    HttpURLConnection connection = (HttpURLConnection) uploadURL.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
    connection.setFixedLengthStreamingMode(bytes.length);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.connect();

    try {
        try (OutputStream os = connection.getOutputStream()) {
            os.write(bytes);
        }

        try (InputStream is = connection.getInputStream()) {
            JsonObject json = new Gson().fromJson(new InputStreamReader(is), JsonObject.class);
            return baseUrl + "/" + json.get("key").getAsString() + (extension == null || extension.isEmpty() ? "" : "." + extension);
        }
    } finally {
        connection.disconnect();
    }
}
 
Example 4
Source File: IncendoPaster.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Upload the paste and return the status message
 *
 * @return Status message
 * @throws Throwable any and all exceptions
 */
public final String upload() throws Throwable {
    final URL url = new URL(UPLOAD_PATH);
    final URLConnection connection = url.openConnection();
    final HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setDoOutput(true);
    final byte[] content = toJsonString().getBytes(Charsets.UTF_8);
    httpURLConnection.setFixedLengthStreamingMode(content.length);
    httpURLConnection.setRequestProperty("Content-Type", "application/json");
    httpURLConnection.setRequestProperty("Accept", "*/*");
    httpURLConnection.connect();
    try (final OutputStream stream = httpURLConnection.getOutputStream()) {
        stream.write(content);
    }
    if (!httpURLConnection.getResponseMessage().contains("OK")) {
        throw new IllegalStateException(String.format("Server returned status: %d %s",
                httpURLConnection.getResponseCode(), httpURLConnection.getResponseMessage()));
    }
    final StringBuilder input = new StringBuilder();
    try (final BufferedReader inputStream = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
        String line;
        while ((line = inputStream.readLine()) != null) {
            input.append(line).append("\n");
        }
    }
    return input.toString();
}
 
Example 5
Source File: FixedLengthInputStream.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
void test(String[] args) throws IOException {
    HttpServer httpServer = startHttpServer();
    int port = httpServer.getAddress().getPort();
    try {
        URL url = new URL("http://localhost:" + port + "/flis/");
        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
        uc.setDoOutput(true);
        uc.setRequestMethod("POST");
        uc.setFixedLengthStreamingMode(POST_SIZE);
        OutputStream os = uc.getOutputStream();

        /* create a 32K byte array with data to POST */
        int thirtyTwoK = 32 * 1024;
        byte[] ba = new byte[thirtyTwoK];
        for (int i =0; i<thirtyTwoK; i++)
            ba[i] = (byte)i;

        long times = POST_SIZE / thirtyTwoK;
        for (int i=0; i<times; i++) {
            os.write(ba);
        }

        os.close();
        InputStream is = uc.getInputStream();
        while(is.read(ba) != -1);
        is.close();

        pass();
    } finally {
        httpServer.stop(0);
    }
}
 
Example 6
Source File: FixedLengthInputStream.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void test(String[] args) throws IOException {
    HttpServer httpServer = startHttpServer();
    int port = httpServer.getAddress().getPort();
    try {
        URL url = new URL("http://localhost:" + port + "/flis/");
        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
        uc.setDoOutput(true);
        uc.setRequestMethod("POST");
        uc.setFixedLengthStreamingMode(POST_SIZE);
        OutputStream os = uc.getOutputStream();

        /* create a 32K byte array with data to POST */
        int thirtyTwoK = 32 * 1024;
        byte[] ba = new byte[thirtyTwoK];
        for (int i =0; i<thirtyTwoK; i++)
            ba[i] = (byte)i;

        long times = POST_SIZE / thirtyTwoK;
        for (int i=0; i<times; i++) {
            os.write(ba);
        }

        os.close();
        InputStream is = uc.getInputStream();
        while(is.read(ba) != -1);
        is.close();

        pass();
    } finally {
        httpServer.stop(0);
    }
}
 
Example 7
Source File: HttpEngine.java    From lighthttp with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")
private static void setFixedLengthStreamingMode(final HttpURLConnection urlConnection,
        final long contentLength) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        urlConnection.setFixedLengthStreamingMode((int) contentLength);
    } else {
        urlConnection.setFixedLengthStreamingMode(contentLength);
    }
}
 
Example 8
Source File: FixedLengthInputStream.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
void test(String[] args) throws IOException {
    HttpServer httpServer = startHttpServer();
    int port = httpServer.getAddress().getPort();
    try {
        URL url = new URL("http://localhost:" + port + "/flis/");
        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
        uc.setDoOutput(true);
        uc.setRequestMethod("POST");
        uc.setFixedLengthStreamingMode(POST_SIZE);
        OutputStream os = uc.getOutputStream();

        /* create a 32K byte array with data to POST */
        int thirtyTwoK = 32 * 1024;
        byte[] ba = new byte[thirtyTwoK];
        for (int i =0; i<thirtyTwoK; i++)
            ba[i] = (byte)i;

        long times = POST_SIZE / thirtyTwoK;
        for (int i=0; i<times; i++) {
            os.write(ba);
        }

        os.close();
        InputStream is = uc.getInputStream();
        while(is.read(ba) != -1);
        is.close();

        pass();
    } finally {
        httpServer.stop(0);
    }
}
 
Example 9
Source File: ConfigFetchHttpClient.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private void setFetchRequestBody(HttpURLConnection urlConnection, byte[] requestBody)
    throws IOException {
  urlConnection.setFixedLengthStreamingMode(requestBody.length);
  OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
  out.write(requestBody);
  out.flush();
  out.close();
}
 
Example 10
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testCannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
    server.play();
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
    connection.setFixedLengthStreamingMode(1);
    try {
        connection.setChunkedStreamingMode(1);
        fail();
    } catch (IllegalStateException expected) {
    }
}
 
Example 11
Source File: JSONParser.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
public static String sendToUrl(final URL url, final String data) throws IOException 
{
    final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        
        urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
        urlConnection.setReadTimeout(READ_TIMEOUT);
        
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setRequestProperty("Accept", "application/json");
        
        final byte[] bytes = data.getBytes(Charset.forName("UTF-8"));
        urlConnection.setFixedLengthStreamingMode(bytes.length);
        urlConnection.getOutputStream().write(bytes);
        
        final StringBuilder stringBuilder = new StringBuilder();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        int read;
        final char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            stringBuilder.append(chars, 0, read);
        return stringBuilder.toString();
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 12
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testCannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
    server.play();
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
    connection.setChunkedStreamingMode(1);
    try {
        connection.setFixedLengthStreamingMode(1);
        fail();
    } catch (IllegalStateException expected) {
    }
}
 
Example 13
Source File: FileRequest.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a HttpURLConnection to set the file's properties, Sign with zero length specified.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param fileOptions
 *            A {@link FileRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@link CloudFileClient}.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @param accessCondition
 *            An {@link AccessCondition} object that represents the access conditions for the file.
 * @param properties
 *            The properties to upload.
 * @return a HttpURLConnection to use to perform the operation.
 * @throws IOException
 *             if there is an error opening the connection
 * @throws URISyntaxException
 *             if the resource URI is invalid
 * @throws StorageException
 *             an exception representing any error which occurred during the operation.
 * @throws IllegalArgumentException
 */
public static HttpURLConnection setFileProperties(final URI uri, final FileRequestOptions fileOptions,
        final OperationContext opContext, final AccessCondition accessCondition, final FileProperties properties)
        throws IOException, URISyntaxException, StorageException {
    final UriQueryBuilder builder = new UriQueryBuilder();
    builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES);

    final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext);

    request.setFixedLengthStreamingMode(0);
    request.setDoOutput(true);
    request.setRequestMethod(Constants.HTTP_PUT);

    if (accessCondition != null) {
        accessCondition.applyConditionToRequest(request);
    }

    if (properties != null) {
        addProperties(request, properties);
    }

    return request;
}
 
Example 14
Source File: Client.java    From feign with Apache License 2.0 4 votes vote down vote up
HttpURLConnection convertAndSend(Request request, Options options) throws IOException {
  final URL url = new URL(request.url());
  final HttpURLConnection connection = this.getConnection(url);
  if (connection instanceof HttpsURLConnection) {
    HttpsURLConnection sslCon = (HttpsURLConnection) connection;
    if (sslContextFactory != null) {
      sslCon.setSSLSocketFactory(sslContextFactory);
    }
    if (hostnameVerifier != null) {
      sslCon.setHostnameVerifier(hostnameVerifier);
    }
  }
  connection.setConnectTimeout(options.connectTimeoutMillis());
  connection.setReadTimeout(options.readTimeoutMillis());
  connection.setAllowUserInteraction(false);
  connection.setInstanceFollowRedirects(options.isFollowRedirects());
  connection.setRequestMethod(request.httpMethod().name());

  Collection<String> contentEncodingValues = request.headers().get(CONTENT_ENCODING);
  boolean gzipEncodedRequest =
      contentEncodingValues != null && contentEncodingValues.contains(ENCODING_GZIP);
  boolean deflateEncodedRequest =
      contentEncodingValues != null && contentEncodingValues.contains(ENCODING_DEFLATE);

  boolean hasAcceptHeader = false;
  Integer contentLength = null;
  for (String field : request.headers().keySet()) {
    if (field.equalsIgnoreCase("Accept")) {
      hasAcceptHeader = true;
    }
    for (String value : request.headers().get(field)) {
      if (field.equals(CONTENT_LENGTH)) {
        if (!gzipEncodedRequest && !deflateEncodedRequest) {
          contentLength = Integer.valueOf(value);
          connection.addRequestProperty(field, value);
        }
      } else {
        connection.addRequestProperty(field, value);
      }
    }
  }
  // Some servers choke on the default accept string.
  if (!hasAcceptHeader) {
    connection.addRequestProperty("Accept", "*/*");
  }

  if (request.body() != null) {
    if (disableRequestBuffering) {
      if (contentLength != null) {
        connection.setFixedLengthStreamingMode(contentLength);
      } else {
        connection.setChunkedStreamingMode(8196);
      }
    }
    connection.setDoOutput(true);
    OutputStream out = connection.getOutputStream();
    if (gzipEncodedRequest) {
      out = new GZIPOutputStream(out);
    } else if (deflateEncodedRequest) {
      out = new DeflaterOutputStream(out);
    }
    try {
      out.write(request.body());
    } finally {
      try {
        out.close();
      } catch (IOException suppressed) { // NOPMD
      }
    }
  }
  return connection;
}
 
Example 15
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a HttpURLConnection to create a snapshot of the blob. Sign with 0 length.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param blobOptions
 *            A {@link BlobRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@link CloudBlobClient}.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @param accessCondition
 *            An {@link AccessCondition} object that represents the access conditions for the blob.
 * @return a HttpURLConnection to use to perform the operation.
 * @throws IOException
 *             if there is an error opening the connection
 * @throws URISyntaxException
 *             if the resource URI is invalid
 * @throws StorageException
 *             an exception representing any error which occurred during the operation.
 * @throws IllegalArgumentException
 */
public static HttpURLConnection snapshot(final URI uri, final BlobRequestOptions blobOptions,
        final OperationContext opContext, final AccessCondition accessCondition) throws IOException,
        URISyntaxException, StorageException {
    final UriQueryBuilder builder = new UriQueryBuilder();
    builder.add(Constants.QueryConstants.COMPONENT, BlobConstants.SNAPSHOT);
    final HttpURLConnection request = createURLConnection(uri, builder, blobOptions, opContext);

    request.setFixedLengthStreamingMode(0);
    request.setDoOutput(true);
    request.setRequestMethod(Constants.HTTP_PUT);

    if (accessCondition != null) {
        accessCondition.applyConditionToRequest(request);
    }

    return request;
}
 
Example 16
Source File: AjaxHttpRequest.java    From lizzie with GNU General Public License v3.0 4 votes vote down vote up
protected void sendSync(String content) throws IOException {
  if (sent) {
    return;
  }
  try {
    URLConnection c;
    synchronized (this) {
      c = this.connection;
    }
    if (c == null) {
      return;
    }
    sent = true;
    initConnectionRequestHeader(c);
    int istatus;
    String istatusText;
    InputStream err;
    if (c instanceof HttpURLConnection) {
      HttpURLConnection hc = (HttpURLConnection) c;
      String method = this.requestMethod == null ? DEFAULT_REQUEST_METHOD : this.requestMethod;

      method = method.toUpperCase();
      hc.setRequestMethod(method);
      if ("POST".equals(method) && content != null) {
        hc.setDoOutput(true);
        byte[] contentBytes = content.getBytes(postCharset);
        hc.setFixedLengthStreamingMode(contentBytes.length);
        OutputStream out = hc.getOutputStream();
        try {
          out.write(contentBytes);
        } finally {
          out.flush();
        }
      }
      istatus = hc.getResponseCode();
      istatusText = hc.getResponseMessage();
      err = hc.getErrorStream();
    } else {
      istatus = 0;
      istatusText = "";
      err = null;
    }
    synchronized (this) {
      this.responseHeaders = getConnectionResponseHeaders(c);
      this.responseHeadersMap = c.getHeaderFields();
    }
    this.changeState(AjaxHttpRequest.STATE_LOADED, istatus, istatusText, null);
    InputStream in = err == null ? c.getInputStream() : err;
    int contentLength = c.getContentLength();

    this.changeState(AjaxHttpRequest.STATE_INTERACTIVE, istatus, istatusText, null);
    byte[] bytes = loadStream(in, contentLength == -1 ? 4096 : contentLength);
    this.changeState(AjaxHttpRequest.STATE_COMPLETE, istatus, istatusText, bytes);
  } finally {
    synchronized (this) {
      this.connection = null;
      sent = false;
    }
  }
}
 
Example 17
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
     * Test that request body chunking works. This test has been relaxed from treating
     * the {@link java.net.HttpURLConnection#setChunkedStreamingMode(int)}
     * chunk length as being fixed because OkHttp no longer guarantees
     * the fixed chunk size. Instead, we check that chunking takes place
     * and we force the chunk size with flushes.
     */
//    public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
//        server.enqueue(new MockResponse());
//        server.play();
//
//        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
//        // Later releases of Android ignore the value for chunkLength if it is > 0 and default to
//        // a fixed chunkLength. During the change-over period while the chunkLength indicates the
//        // chunk buffer size (inc. header) the chunkLength has to be >= 8. This enables the flush()
//        // to dictate the size of the chunks.
//        urlConnection.setChunkedStreamingMode(50 /* chunkLength */);
//        urlConnection.setDoOutput(true);
//        OutputStream outputStream = urlConnection.getOutputStream();
//        String outputString = "ABCDEFGH";
//        byte[] outputBytes = outputString.getBytes("US-ASCII");
//        int targetChunkSize = 3;
//        for (int i = 0; i < outputBytes.length; i += targetChunkSize) {
//            int count = i + targetChunkSize < outputBytes.length ? 3 : outputBytes.length - i;
//            outputStream.write(outputBytes, i, count);
//            outputStream.flush();
//        }
//        assertEquals(200, urlConnection.getResponseCode());
//
//        RecordedRequest request = server.takeRequest();
//        assertEquals(outputString, new String(request.getBody(), "US-ASCII"));
//        assertEquals(Arrays.asList(3, 3, 2), request.getChunkSizes());
//    }

// TODO(tball): b/28067294
//    public void testAuthenticateWithFixedLengthStreaming() throws Exception {
//        testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
//    }

// TODO(tball): b/28067294
//    public void testAuthenticateWithChunkedStreaming() throws Exception {
//        testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
//    }

    private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
        MockResponse pleaseAuthenticate = new MockResponse()
                .setResponseCode(401)
                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
                .setBody("Please authenticate.");
        server.enqueue(pleaseAuthenticate);
        server.play();

        Authenticator.setDefault(new SimpleAuthenticator());
        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
        connection.setDoOutput(true);
        byte[] requestBody = { 'A', 'B', 'C', 'D' };
        if (streamingMode == StreamingMode.FIXED_LENGTH) {
            connection.setFixedLengthStreamingMode(requestBody.length);
        } else if (streamingMode == StreamingMode.CHUNKED) {
            connection.setChunkedStreamingMode(0);
        }
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(requestBody);
        outputStream.close();
        try {
            connection.getInputStream();
            fail();
        } catch (HttpRetryException expected) {
        }

        // no authorization header for the request...
        RecordedRequest request = server.takeRequest();
        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
    }
 
Example 18
Source File: OkHttpConnectFactory.java    From Kalle with Apache License 2.0 4 votes vote down vote up
@Override
public Connection connect(Request request) throws IOException {
    URL url = new URL(request.url().toString(true));
    Proxy proxy = request.proxy();
    HttpURLConnection connection = open(url, proxy);

    connection.setConnectTimeout(request.connectTimeout());
    connection.setReadTimeout(request.readTimeout());
    connection.setInstanceFollowRedirects(false);

    if (connection instanceof HttpsURLConnection) {
        SSLSocketFactory sslSocketFactory = request.sslSocketFactory();
        if (sslSocketFactory != null)
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        HostnameVerifier hostnameVerifier = request.hostnameVerifier();
        if (hostnameVerifier != null)
            ((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier);
    }

    RequestMethod method = request.method();
    connection.setRequestMethod(method.toString());
    connection.setDoInput(true);
    boolean isAllowBody = method.allowBody();
    connection.setDoOutput(isAllowBody);

    Headers headers = request.headers();

    if (isAllowBody) {
        long contentLength = headers.getContentLength();
        if (contentLength <= Integer.MAX_VALUE) connection.setFixedLengthStreamingMode((int) contentLength);
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) connection.setFixedLengthStreamingMode(contentLength);
        else connection.setChunkedStreamingMode(256 * 1024);
    }

    Map<String, String> requestHeaders = Headers.getRequestHeaders(headers);
    for (Map.Entry<String, String> headerEntry : requestHeaders.entrySet()) {
        String headKey = headerEntry.getKey();
        String headValue = headerEntry.getValue();
        connection.setRequestProperty(headKey, headValue);
    }

    connection.connect();
    return new URLConnection(connection);
}
 
Example 19
Source File: Common.java    From samples with MIT License 4 votes vote down vote up
public static String generateUploadURL(String filePath, int appId) {
    try {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("filename", filePath);
        if (appId != 0) {
            jsonObject.addProperty("appId", appId);
        }

        URL obj = new URL("https://api.kobiton.com/v1/apps/uploadUrl");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setFixedLengthStreamingMode(jsonObject.toString().getBytes().length);
        con.setRequestProperty("Authorization", generateBasicAuth());

        OutputStream os = new BufferedOutputStream(con.getOutputStream());
        os.write(jsonObject.toString().getBytes());
        os.flush();

        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();
        String result = response.toString();
        System.out.println("generateUploadURL: " + result);
        return result;

    } catch (Exception ex) {
        System.out.println(ex.toString());
        return null;
    }
}
 
Example 20
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 3 votes vote down vote up
/**
 * Constructs a HttpURLConnection to upload a page. Sign with page length for update, or 0 for clear.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param blobOptions
 *            A {@link BlobRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@link CloudBlobClient}.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @param accessCondition
 *            An {@link AccessCondition} object that represents the access conditions for the blob.
 * @param pageRange
 *            A {@link PageRange} object that represents the page range.
 * @param operationType
 *            A {@link PageOperationType} object that represents the page range operation type.
 * @return a HttpURLConnection to use to perform the operation.
 * @throws IOException
 *             if there is an error opening the connection
 * @throws URISyntaxException
 *             if the resource URI is invalid
 * @throws StorageException
 *             an exception representing any error which occurred during the operation.
 * @throws IllegalArgumentException
 */
public static HttpURLConnection putPage(final URI uri, final BlobRequestOptions blobOptions,
        final OperationContext opContext, final AccessCondition accessCondition, final PageRange pageRange,
        final PageOperationType operationType) throws IOException, URISyntaxException, StorageException {
    final UriQueryBuilder builder = new UriQueryBuilder();
    builder.add(Constants.QueryConstants.COMPONENT, PAGE_QUERY_ELEMENT_NAME);

    final HttpURLConnection request = createURLConnection(uri, builder, blobOptions, opContext);

    request.setDoOutput(true);
    request.setRequestMethod(Constants.HTTP_PUT);

    if (operationType == PageOperationType.CLEAR) {
        request.setFixedLengthStreamingMode(0);
    }

    // Page write is either update or clean; required
    request.setRequestProperty(BlobConstants.PAGE_WRITE, operationType.toString());
    request.setRequestProperty(Constants.HeaderConstants.STORAGE_RANGE_HEADER, pageRange.toString());

    if (accessCondition != null) {
        accessCondition.applyConditionToRequest(request);
        accessCondition.applySequenceConditionToRequest(request);
    }

    return request;
}