Example usage for org.apache.http.client.methods HttpUriRequest setHeader

List of usage examples for org.apache.http.client.methods HttpUriRequest setHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest setHeader.

Prototype

void setHeader(String str, String str2);

Source Link

Usage

From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java

private String updateDeplymentStatus(HttpUriRequest request, UpdateStatus status,
        AsyncResultCallback callback) {/*from ww w  . java2 s .  c o m*/
    String template = "<UpdateDeploymentStatus xmlns=\"http://schemas.microsoft.com/windowsazure\"><Status>{0}</Status></UpdateDeploymentStatus>";
    request.setHeader(HeaderNames.ContentType, APPLICATION_XML);
    return sendAsyncPostRequest(request, callback, template, status.getLiteral());
}

From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java

/**
 * The Get Hosted Service Properties operation retrieves system properties
 * for the specified hosted service. These properties include the service
 * name and service type; the name of the affinity group to which the
 * service belongs, or its location if it is not part of an affinity group;
 * and optionally, information on the service's deployments. When the
 * request sets the embed-detail parameter to true, the response body
 * includes additional details on the service's deployments:
 *///w  ww.jav a2  s.  c o  m
public HostedServiceProperties getHostedServiceProperties(String serviceName, boolean embedDetail) {
    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(URI.create(getBaseUrl()
            + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName + "?embed-detail=" + embedDetail),
            HttpMethod.Get);
    request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2011_06_01);

    try {
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
        if (isRequestAccepted(response)) {
            return XPathQueryHelper.parseHostedPropertiesResponse(response.getStream());
        } else {
            HttpUtilities.processUnexpectedStatusCode(response);
        }
    } catch (StorageException we) {
        throw HttpUtilities.translateWebException(we);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return null;
}

From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java

@Override
public String createLinuxVirtualMachineDeployment(String serviceName, String deploymentName, String label,
        String roleName, String hostName, String username, String newPassword, String OSImageLink,
        String imageName, String roleSize, AsyncResultCallback callback) {
    if (deploymentName == null)
        throw new IllegalArgumentException("Service name is required!");
    if (label == null)
        throw new IllegalArgumentException("Service label is required!");

    //if (isServiceExist(deploymentName))
    //throw new IllegalArgumentException("Service already exist!");
    /*/*from  w  w  w.  ja  v  a 2 s  .  c om*/
          getBaseUrl() + SERVICES_HOSTEDSERVICES
          + ConstChars.Slash + serviceName + DEPLOYMENTS
          + ConstChars.Slash + deploymentName + ConstChars.Slash
          + ROLE_INSTANCES + ConstChars.Slash + roleInstanceName
          + "?comp=reimage")*/

    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(
            URI.create(getBaseUrl() + SERVICES_VIRTUALMACHINE + ConstChars.Slash + serviceName + DEPLOYMENTS),
            HttpMethod.Post);

    request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2012_03_01);
    request.addHeader(HeaderNames.ContentType, APPLICATION_XML);

    String base64Label = Base64.encode(label.getBytes());
    String body = MessageFormat.format(CREATE_VIRTUALMACHINE, deploymentName, label, roleName, hostName,
            username, newPassword, OSImageLink, imageName, roleSize);

    System.out.println(body);

    ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes()));
    return sendAsynchronousRequest(request, callback);

    // body =
    // "<?xml version=\"1.0\"?><CreateDeployment xmlns=\"http://schemas.microsoft.com/windowsazure\"><Name>testdep</Name><PackageUrl>http://soyatecdemo.blob.core.windows.net/manageusage/simpletest</PackageUrl><Label>c2ltcGxldGVzdA==</Label><Configuration>PD94bWwgdmVyc2lvbj0iMS4wIj8+PFNlcnZpY2VDb25maWd1cmF0aW9uIHNlcnZpY2VOYW1lPSJzaW1wbGV0ZXN0IiB4bWxucz0iaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS9TZXJ2aWNlSG9zdGluZy8yMDA4LzEwL1NlcnZpY2VDb25maWd1cmF0aW9uIj4gIDxSb2xlIG5hbWU9IldlYlJvbGUiPiAgICA8SW5zdGFuY2VzIGNvdW50PSIxIi8+ICAgIDxDb25maWd1cmF0aW9uU2V0dGluZ3M+ICAgIDwvQ29uZmlndXJhdGlvblNldHRpbmdzPiAgPC9Sb2xlPjwvU2VydmljZUNvbmZpZ3VyYXRpb24+</Configuration></CreateDeployment>";

}

From source file:com.seo.support.http.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 * //from w w  w. j a v a 2  s .  com
 * @param client
 *            HttpClient to be used for request, can differ in single
 *            requests
 * @param contentType
 *            MIME body type, for POST and PUT requests, may be null
 * @param context
 *            Context of Android application, to hold the reference of
 *            request
 * @param httpContext
 *            HttpContext in which the request will be executed
 * @param responseHandler
 *            ResponseHandler or its subclass to put the response into
 * @param uriRequest
 *            instance of HttpUriRequest, which means it must be of
 *            HttpDelete, HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 */
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (uriRequest == null) {
        throw new IllegalArgumentException("HttpUriRequest must not be null");
    }

    if (responseHandler == null) {
        throw new IllegalArgumentException("ResponseHandler must not be null");
    }

    if (responseHandler.getUseSynchronousMode()) {
        throw new IllegalArgumentException(
                "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.");
    }

    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    AsyncHttpRequest request = new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler);
    threadPool.submit(request);
    RequestHandle requestHandle = new RequestHandle(request);
    if (context != null) {
        // Add request to request map
        List<RequestHandle> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList();
            requestMap.put(context, requestList);
        }

        if (responseHandler instanceof RangeFileAsyncHttpResponseHandler)
            ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest);

        requestList.add(requestHandle);

        Iterator<RequestHandle> iterator = requestList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().shouldBeGarbageCollected()) {
                iterator.remove();
            }
        }
    }

    return requestHandle;
}

From source file:cn.openwatch.internal.http.loopj.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single
 *                        requests//from   w  w  w.j ava  2s  . c  o m
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of
 *                        request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of
 *                        HttpDelete, HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 */
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (uriRequest == null) {
        throw new IllegalArgumentException("HttpUriRequest must not be null");
    }

    if (responseHandler == null) {
        throw new IllegalArgumentException("ResponseHandler must not be null");
    }

    if (responseHandler.getUseSynchronousMode() && !responseHandler.getUsePoolThread()) {
        throw new IllegalArgumentException(
                "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.");
    }

    if (contentType != null) {
        if (uriRequest instanceof HttpEntityEnclosingRequestBase
                && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null
                && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) {
        } else {
            uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType);
        }
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType,
            responseHandler, context);
    threadPool.submit(request);
    RequestHandle requestHandle = new RequestHandle(request);

    if (context != null) {
        List<RequestHandle> requestList;
        // Add request to request map
        synchronized (requestMap) {
            requestList = requestMap.get(context);
            if (requestList == null) {
                requestList = Collections.synchronizedList(new LinkedList<RequestHandle>());
                requestMap.put(context, requestList);
            }
        }

        requestList.add(requestHandle);

        Iterator<RequestHandle> iterator = requestList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().shouldBeGarbageCollected()) {
                iterator.remove();
            }
        }
    }

    return requestHandle;
}

From source file:org.jets3t.service.CloudFrontService.java

/**
 * Sign the given HTTP method object using the AWS credentials provided
 * by {@link #getAWSCredentials()}./*from   w  w w  .  j ava 2 s.  co  m*/
 *
 * @param httpMethod the request object
 * @param context
 * @param ignoredForceRequestSignatureVersion
 * ignored parameter relevant only for AWS4-HMAC-SHA256 request signing.
 * @throws ServiceException
 */
public void authorizeHttpRequest(HttpUriRequest httpMethod, HttpContext context,
        String ignoredForceRequestSignatureVersion) throws ServiceException {
    String date = ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset());

    // Set/update the date timestamp to the current time
    // Note that this will be over-ridden if an "x-amz-date" header is present.
    httpMethod.setHeader("Date", date);

    // Sign the date to authenticate the request.
    // Sign the canonical string.
    String signature = ServiceUtils.signWithHmacSha1(getAWSCredentials().getSecretKey(), date);

    // Add encoded authorization to connection as HTTP Authorization header.
    String authorizationString = "AWS " + getAWSCredentials().getAccessKey() + ":" + signature;
    httpMethod.setHeader("Authorization", authorizationString);
}

From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java

private String changeDeploymentConfiguration(HttpUriRequest request, String configurationBase64,
        AsyncResultCallback callback) {/*  w ww. j  a  v a  2  s.co  m*/
    String template = "<ChangeConfiguration xmlns=\"http://schemas.microsoft.com/windowsazure\"><Configuration>{0}</Configuration></ChangeConfiguration>";
    // String configurationFile = readBase64(configurationFileUrl);

    request.setHeader(HeaderNames.ContentType, APPLICATION_XML);// MEIDA_TYPE_TEXT_XML);
    return sendAsyncPostRequest(request, callback, template, configurationBase64);
    // "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTE2Ij8+DQo8U2VydmljZUNvbmZpZ3VyYXRpb24geG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYS1pbnN0YW5jZSIgeG1sbnM6eHNkPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYSIgc2VydmljZU5hbWU9IiIgeG1sbnM9Imh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vU2VydmljZUhvc3RpbmcvMjAwOC8xMC9TZXJ2aWNlQ29uZmlndXJhdGlvbiI+DQogIDxSb2xlIG5hbWU9IldlYlJvbGUiPg0KICAgIDxDb25maWd1cmF0aW9uU2V0dGluZ3MgLz4NCiAgICA8SW5zdGFuY2VzIGNvdW50PSIxIiAvPg0KICAgIDxDZXJ0aWZpY2F0ZXMgLz4NCiAgPC9Sb2xlPg0KPC9TZXJ2aWNlQ29uZmlndXJhdGlvbj4=");
}

From source file:org.codegist.crest.HttpClientRestService.java

private static HttpUriRequest toHttpUriRequest(HttpRequest request) throws UnsupportedEncodingException {
    HttpUriRequest uriRequest;

    String queryString = "";
    if (request.getQueryParams() != null) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }//from   w  w w . j  a  va 2 s.co m
        String qs = URLEncodedUtils.format(params, request.getEncoding());
        queryString = Strings.isNotBlank(qs) ? ("?" + qs) : "";
    }
    String uri = request.getUri().toString() + queryString;

    switch (request.getMeth()) {
    default:
    case GET:
        uriRequest = new HttpGet(uri);
        break;
    case POST:
        uriRequest = new HttpPost(uri);
        break;
    case PUT:
        uriRequest = new HttpPut(uri);
        break;
    case DELETE:
        uriRequest = new HttpDelete(uri);
        break;
    case HEAD:
        uriRequest = new HttpHead(uri);
        break;
    }
    if (uriRequest instanceof HttpEntityEnclosingRequestBase) {
        HttpEntityEnclosingRequestBase enclosingRequestBase = ((HttpEntityEnclosingRequestBase) uriRequest);
        HttpEntity entity;
        if (Params.isForUpload(request.getBodyParams().values())) {
            MultipartEntity multipartEntity = new MultipartEntity();
            for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) {
                ContentBody body;
                if (param.getValue() instanceof InputStream) {
                    body = new InputStreamBody((InputStream) param.getValue(), param.getKey());
                } else if (param.getValue() instanceof File) {
                    body = new FileBody((File) param.getValue());
                } else if (param.getValue() != null) {
                    body = new StringBody(param.getValue().toString(), request.getEncodingAsCharset());
                } else {
                    body = new StringBody(null);
                }
                multipartEntity.addPart(param.getKey(), body);
            }
            entity = multipartEntity;
        } else {
            List<NameValuePair> params = new ArrayList<NameValuePair>(request.getBodyParams().size());
            for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) {
                params.add(new BasicNameValuePair(param.getKey(),
                        param.getValue() != null ? param.getValue().toString() : null));
            }
            entity = new UrlEncodedFormEntity(params, request.getEncoding());
        }

        enclosingRequestBase.setEntity(entity);
    }

    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
        for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
            uriRequest.setHeader(header.getKey(), header.getValue());
        }
    }

    if (request.getConnectionTimeout() != null && request.getConnectionTimeout() >= 0) {
        HttpConnectionParams.setConnectionTimeout(uriRequest.getParams(),
                request.getConnectionTimeout().intValue());
    }

    if (request.getSocketTimeout() != null && request.getSocketTimeout() >= 0) {
        HttpConnectionParams.setSoTimeout(uriRequest.getParams(), request.getSocketTimeout().intValue());
    }

    return uriRequest;
}

From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java

/**
 * The Swap Deployment operation initiates a virtual IP swap between the
 * staging and production deployment slots for a service. If the service is
 * currently running in the staging environment, it will be swapped to the
 * production environment. If it is running in the production environment,
 * it will be swapped to staging./* w w w .j a  v  a  2 s  .  com*/
 * 
 * @param serviceName
 * @param productName
 * @param sourceName
 * @param callback
 * @return
 */
public String swapDeployment(String serviceName, String productName, String sourceName,
        AsyncResultCallback callback) {
    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(
            URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName),
            HttpMethod.Post);
    String template = "<Swap xmlns=\"http://schemas.microsoft.com/windowsazure\"><Production>{0}</Production><SourceDeployment>{1}</SourceDeployment></Swap>";
    request.setHeader(HeaderNames.ContentType, APPLICATION_XML);
    return sendAsyncPostRequest(request, callback, template, productName, sourceName);
}

From source file:org.attribyte.api.http.impl.commons.Commons4Client.java

@Override
public Response send(Request request, RequestOptions options) throws IOException {

    HttpUriRequest commonsRequest = null;

    switch (request.getMethod()) {
    case GET://  w  ww .  ja  va  2 s  .  c  om
        commonsRequest = new HttpGet(request.getURI());
        break;
    case DELETE:
        commonsRequest = new HttpDelete(request.getURI());
        break;
    case HEAD:
        commonsRequest = new HttpHead(request.getURI());
        break;
    case POST: {
        HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPost(request.getURI());
        commonsRequest = entityEnclosingRequest;
        EntityBuilder entityBuilder = EntityBuilder.create();
        if (request.getBody() != null) {
            entityBuilder.setBinary(request.getBody().toByteArray());
        } else {
            Collection<Parameter> parameters = request.getParameters();
            List<NameValuePair> nameValuePairs = Lists.newArrayListWithExpectedSize(parameters.size());
            for (Parameter parameter : parameters) {
                String[] values = parameter.getValues();
                for (String value : values) {
                    nameValuePairs.add(new BasicNameValuePair(parameter.getName(), value));
                }
            }
        }
        entityEnclosingRequest.setEntity(entityBuilder.build());
        break;
    }
    case PUT: {
        HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPut(request.getURI());
        commonsRequest = entityEnclosingRequest;
        EntityBuilder entityBuilder = EntityBuilder.create();
        if (request.getBody() != null) {
            entityBuilder.setBinary(request.getBody().toByteArray());
        }
        entityEnclosingRequest.setEntity(entityBuilder.build());
        break;
    }
    }

    Collection<Header> headers = request.getHeaders();
    for (Header header : headers) {
        String[] values = header.getValues();
        for (String value : values) {
            commonsRequest.setHeader(header.getName(), value);
        }
    }

    ResponseBuilder builder = new ResponseBuilder();
    CloseableHttpResponse response = null;
    InputStream is = null;
    try {
        if (options.followRedirects != RequestOptions.DEFAULT_FOLLOW_REDIRECTS) {
            RequestConfig localConfig = RequestConfig.copy(defaultRequestConfig)
                    .setRedirectsEnabled(options.followRedirects)
                    .setMaxRedirects(options.followRedirects ? 5 : 0).build();
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setRequestConfig(localConfig);
            response = httpClient.execute(commonsRequest, localContext);
        } else {
            response = httpClient.execute(commonsRequest);
        }

        builder.setStatusCode(response.getStatusLine().getStatusCode());
        for (org.apache.http.Header header : response.getAllHeaders()) {
            builder.addHeader(header.getName(), header.getValue());

        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            is = entity.getContent();
            if (is != null) {
                builder.setBody(Request.bodyFromInputStream(is, options.maxResponseBytes));
            }
        }

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                //TODO?
            }
        }
        if (response != null) {
            response.close();
        }
    }

    return builder.create();
}