Direct Uploads the media.

@param initiationRequestUrl The request URL where the initiation request will be sent
@return HTTP response
16568
private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException {
    updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS);

    HttpContent content = mediaContent;
    if (metadata != null) {
      content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent));
      initiationRequestUrl.put("uploadType", "multipart");
    } else {
      initiationRequestUrl.put("uploadType", "media");
    }
    HttpRequest request =
        requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
    request.getHeaders().putAll(initiationHeaders);
    // We do not have to do anything special here if media content length is unspecified because
    // direct media upload works even when the media content length == -1.
    HttpResponse response = executeCurrentRequest(request);
    boolean responseProcessed = false;
    try {
      if (isMediaLengthKnown()) {
        totalBytesServerReceived = getMediaContentLength();
      }
      updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE);
      responseProcessed = true;
    } finally {
      if (!responseProcessed) {
        response.disconnect();
      }
    }
    return response;
  }
71993
public MediaHttpUploader setInitiationRequestMethod(String initiationRequestMethod) {
    Preconditions.checkArgument(initiationRequestMethod.equals(HttpMethods.POST)
        || initiationRequestMethod.equals(HttpMethods.PUT)
        || initiationRequestMethod.equals(HttpMethods.PATCH));
    this.initiationRequestMethod = initiationRequestMethod;
    return this;
  }
673520
public void sendRedirect(String url) 
        throws IOException
    {
        if (url==null)
            throw new IllegalArgumentException();
        
        if (!URI.hasScheme(url))
        {
            StringBuffer buf = _servletHttpRequest.getHttpRequest().getRootURL();
            if (url.startsWith("/"))
                buf.append(URI.canonicalPath(url));
            else
            {
                String path=_servletHttpRequest.getRequestURI();
                String parent=(path.endsWith("/"))?path:URI.parentPath(path);
                url=URI.canonicalPath(URI.addPaths(parent,url));
                if (!url.startsWith("/"))
                    buf.append('/');
                buf.append(url);
            }
            
            url=buf.toString();
        }
        
        resetBuffer();
        
        _httpResponse.setField(HttpFields.__Location,url);
        _httpResponse.setStatus(HttpResponse.__302_Moved_Temporarily);
        complete();
    }
924974
private String initiateMultipartUpload(CopyObjectRequest origReq) {

        InitiateMultipartUploadRequest req = new InitiateMultipartUploadRequest(
                origReq.getDestinationBucketName(),
                origReq.getDestinationKey()).withCannedACL(
                origReq.getCannedAccessControlList())
                .withRequesterPays(origReq.isRequesterPays())
                .withAccessControlList(origReq.getAccessControlList())
                .withStorageClass(origReq.getStorageClass())
                .withSSECustomerKey(origReq.getDestinationSSECustomerKey())
                .withSSEAwsKeyManagementParams(origReq.getSSEAwsKeyManagementParams())
                .withGeneralProgressListener(origReq.getGeneralProgressListener())
                .withRequestMetricCollector(origReq.getRequestMetricCollector())
           ;

        ObjectMetadata newObjectMetadata = origReq.getNewObjectMetadata();
        if (newObjectMetadata == null){
            newObjectMetadata = new ObjectMetadata();
        }
        if (newObjectMetadata.getContentType() == null){
            newObjectMetadata.setContentType(metadata.getContentType());
        }

        req.setObjectMetadata(newObjectMetadata);

        populateMetadataWithEncryptionParams(metadata,newObjectMetadata);

        String uploadId = s3.initiateMultipartUpload(req).getUploadId();
        log.debug("Initiated new multipart upload: " + uploadId);

        return uploadId;
    }
766424
private static long uploadImage(MediaServiceInterface mediaService, String url)
      throws IOException {
    // Create image.
    Image image = new Image();
    image.setType(MediaMediaType.IMAGE);
    image.setData(com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl(url));

    // Upload image.
    Image uploadedImage = (Image) mediaService.upload(new Media[] {image})[0];
    return uploadedImage.getMediaId();
  }
1330643
private <T> HttpResponse sendRequest(final URI uri, final HttpRequest<T> request) throws IOException, ProtocolException
	{
		final HttpURLConnection connection;
		try
		{
			connection = mConnectionFactory.httpUrlConnection(uri);
		}
		catch (IllegalArgumentException e)
		{
			throw new ProtocolException("The given URI is not applicable to HTTP requests.", e);
		}
		// ensure the expected redirect behavior
		connection.setInstanceFollowRedirects(false);
		// set the request method
		connection.setDoOutput(request.method().supportsRequestPayload());
		connection.setRequestMethod(request.method().verb());
		// add all headers
		for (Header<?> header : request.headers())
		{
			connection.setRequestProperty(header.type().name(), header.toString());
		}
		// also set the content-type header if we have any content-type
		if (request.requestEntity().contentType() != null)
		{
			connection.setRequestProperty(HttpHeaders.CONTENT_TYPE.name(), HttpHeaders.CONTENT_TYPE.valueString(request.requestEntity().contentType()));
		}
		// send the request entity if applicable
		if (request.method().supportsRequestPayload())
		{
			OutputStream out = connection.getOutputStream();
			try
			{
				request.requestEntity().writeContent(out);
			}
			finally
			{
				out.close();
			}
		}
		// return the response
		return new HttpUrlConnectionResponse(uri, connection);
	}
131949
public Uploader startUploadFileChunked(String targetPath, DbxWriteMode writeMode, long numBytes)
    {
        return startUploadFileChunked(ChunkedUploadChunkSize, targetPath, writeMode, numBytes);
    }
351790
protected String buildRedirectUrlByRequestedAuthnContext(final String initialUrl, final AuthnRequest authnRequest, final HttpServletRequest request) {
        val authenticationContextClassMappings = samlProfileHandlerConfigurationContext.getCasProperties()
            .getAuthn().getSamlIdp().getAuthenticationContextClassMappings();
        if (authnRequest.getRequestedAuthnContext() == null || authenticationContextClassMappings == null || authenticationContextClassMappings.isEmpty()) {
            return initialUrl;
        }

        val mappings = getAuthenticationContextMappings();

        val p =
            authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs()
                .stream()
                .filter(ref -> {
                    val clazz = ref.getAuthnContextClassRef();
                    return mappings.containsKey(clazz);
                })
                .findFirst();

        if (p.isPresent()) {
            val mappedClazz = mappings.get(p.get().getAuthnContextClassRef());
            return initialUrl + '&' + samlProfileHandlerConfigurationContext.getCasProperties()
                .getAuthn().getMfa().getRequestParameter() + '=' + mappedClazz;
        }

        return initialUrl;
    }
1024587
public static UploadimgResult mediaUploadimg(String access_token,URI uri){
		HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/uploadimg");
		CloseableHttpClient tempHttpClient = HttpClients.createDefault();
		try {
			HttpEntity entity = tempHttpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity();
			HttpEntity reqEntity = MultipartEntityBuilder.create()
					 .addBinaryBody("media",EntityUtils.toByteArray(entity),ContentType.get(entity),UUID.randomUUID().toString()+".jpg")
			         .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
			         .build();
			httpPost.setEntity(reqEntity);
			return LocalHttpClient.executeJsonResult(httpPost,UploadimgResult.class);
		} catch (Exception e) {
			logger.error("", e);
		} finally{
			try {
				tempHttpClient.close();
			} catch (Exception e) {
				logger.error("", e);
			}
		}
		return null;
	}
506011
public void upload(final String uri, final File sourceFile, final String contentType)
            throws IOException, AppPlatformException {
        final String path = getPath(uri);
        final HttpPut request = (HttpPut) setupRequest(path, HttpPut.METHOD_NAME, null);
        request.setEntity(contentType == null ? new FileEntity(sourceFile) : new FileEntity(sourceFile, ContentType.parse(contentType)));
        performRequest(request);
    }
1340780
public static HttpRequestor.Response startPostRaw(DbxRequestConfig requestConfig,
                                                      String sdkUserAgentIdentifier,
                                                      String host,
                                                      String path,
                                                      byte[] body,
                                                      /*@Nullable*/List<HttpRequestor.Header> headers)
        throws NetworkIOException {
        String uri = buildUri(host, path);

        headers = copyHeaders(headers);
        headers = addUserAgentHeader(headers, requestConfig, sdkUserAgentIdentifier);
        headers.add(new HttpRequestor.Header("Content-Length", Integer.toString(body.length)));

        try {
            HttpRequestor.Uploader uploader = requestConfig.getHttpRequestor().startPost(uri, headers);
            try {
                uploader.upload(body);
                return uploader.finish();
            } finally {
                uploader.close();
            }
        } catch (IOException ex) {
            throw new NetworkIOException(ex);
        }
    }
1019164
public Response makeRequest(final Request request) {

        HttpMethod method = request.getMethod();
        RequestBuilder builder = RequestBuilder.create(method.toString())
            .setUri(request.constructURL().toString())
            .setVersion(HttpVersion.HTTP_1_1)
            .setCharset(StandardCharsets.UTF_8);

        if (request.requiresAuthentication()) {
            builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString());
        }

        if (method == HttpMethod.POST) {
            builder.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
                for (String value : entry.getValue()) {
                    builder.addParameter(entry.getKey(), value);
                }
            }
        }

        HttpResponse response = null;

        try {
            response = client.execute(builder.build());
            HttpEntity entity = response.getEntity();
            return new Response(
                // Consume the entire HTTP response before returning the stream
                entity == null ? null : new BufferedHttpEntity(entity).getContent(),
                response.getStatusLine().getStatusCode()
            );
        } catch (IOException e) {
            throw new ApiException(e.getMessage(), e);
        } finally {

            // Ensure this response is properly closed
            HttpClientUtils.closeQuietly(response);

        }

    }
1074211
private static HttpResponse sendRequest(org.dasein.cloud.digitalocean.DigitalOcean provider, RESTMethod method, String token, String strUrl, DigitalOceanAction action) throws CloudException, InternalException {
        HttpRequestBase req = null;
        if (method == RESTMethod.GET) {
            req = new HttpGet(strUrl);
        } else if (method == RESTMethod.POST) {
            req = new HttpPost(strUrl);
        } else if (method == RESTMethod.PUT) {
            req = new HttpPut(strUrl);
        } else if (method == RESTMethod.DELETE) {
            req = new HttpDelete(strUrl);
        } else if (method == RESTMethod.HEAD) {
            req = new HttpHead(strUrl);
        }

        try {
            req.setHeader("Authorization", "Bearer " + token);
            req.setHeader("Accept", "application/json");
            req.setHeader("Content-Type", "application/json;charset=UTF-8");

            StringEntity requestEntity = null;
            if (req instanceof HttpEntityEnclosingRequestBase && action != null) {
                JSONObject jsonToPost = action.getParameters();
                if (jsonToPost != null) {
                    requestEntity = new StringEntity(
                            jsonToPost.toString(),
                            ContentType.APPLICATION_JSON);
                    ((HttpEntityEnclosingRequestBase) req).setEntity(requestEntity);
                }
            }

            HttpClient httpClient = provider.getClient();

            if (wire.isDebugEnabled()) {
                wire.debug("");
                wire.debug("--------------------------------------------------------------------------------------");
            }

            if (wire.isDebugEnabled()) {
                wire.debug(req.getRequestLine().toString());
                for (Header header : req.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");

                if (requestEntity != null) {
                    try {
                        wire.debug(EntityUtils.toString(requestEntity));
                        wire.debug("");
                    } catch (IOException ignore) {
                    }
                }
            }

            HttpResponse response = null;
            int retryCount = 0;

            while (retryCount < 6) {
                response = httpClient.execute(req);

                if (wire.isDebugEnabled()) {
                    wire.debug(response.getStatusLine().toString());
                }

                if (method == RESTMethod.DELETE) {
                    if ((response.getStatusLine().getStatusCode() == 204)) {
                        break;
                    } else {
                        retryCount++;
                        Thread.sleep(5000);
                    }
                } else {
                    break;
                }
            }
            if (method == RESTMethod.DELETE && (response.getStatusLine().getStatusCode() != 204)) {
                //Error occurred
                throw new CloudException("Delete method returned unexpected code, despite retrying.");
            }
            return response;
        } catch (JSONException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (InterruptedException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (ClientProtocolException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (IOException e) {
            throw new CloudException("Problem sending request.", e);
        } finally {
            try {
//                req.releaseConnection();
            } catch (Exception e) {
            }

        }
    }
434750
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
		ClientHttpRequest request = getRequestFactory().createRequest(url, method);
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, "Created " + method.name() + " request for \"" + url + "\"");
		}
		return request;
	}
106579
@Override
  protected void initRequest()
  {
    super.initRequest();
    
    _state = _state.toActive();
    
    // HttpBufferStore httpBuffer = getHttpBufferStore();
    HttpBufferStore bufferStore = getHttpBufferStore();

    _method.clear();
    _methodString = null;
    _protocol.clear();

    _uriLength = 0;
    if (bufferStore == null) {
      // server/05h8
      _uri = getSmallUriBuffer(); // httpBuffer.getUriBuffer();
      
      _headerBuffer = getSmallHeaderBuffer(); // httpBuffer.getHeaderBuffer();
      _headerKeys = getSmallHeaderKeys();     // httpBuffer.getHeaderKeys();
      _headerValues = getSmallHeaderValues(); // httpBuffer.getHeaderValues();
    }

    _uriHost.clear();
    _host = null;
    _keepalive = KeepaliveState.INIT;

    _headerSize = 0;
    _headerLength = 0;
    
    _inOffset = 0;
    _isChunkedIn = false;
    _isFirst = true;
  }
207049
public void doWithRequest(
                    final ClientHttpRequest request
                    )
    throws IOException
    {
        HttpHeaders  headers = request.getHeaders();
        headers.setContentType( _mediaType );

        long  size = IoUtil.copy( new StringReader( _string.toString() ),
                        new OutputStreamWriter( request.getBody() ) );
        headers.setContentLength( size );
    }
1285252
protected final InitiateMultipartUploadRequest newInitiateMultipartUploadRequest(
            UploadObjectRequest req) {
        return new InitiateMultipartUploadRequest(
                req.getBucketName(), req.getKey(), req.getMetadata())
            .withRedirectLocation(req.getRedirectLocation())
            .withSSEAwsKeyManagementParams(req.getSSEAwsKeyManagementParams())
            .withSSECustomerKey(req.getSSECustomerKey())
            .withStorageClass(req.getStorageClass())
            .withAccessControlList(req.getAccessControlList())
            .withCannedACL(req.getCannedAcl())
            .withGeneralProgressListener(req.getGeneralProgressListener())
            .withRequestMetricCollector(req.getRequestMetricCollector())
            ;
    }