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:com.yunmall.ymsdk.net.http.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
 * @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
 *//* w  ww .j a  va 2 s .c om*/
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) {
        if (uriRequest instanceof HttpEntityEnclosingRequestBase
                && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null) {
            YmLog.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type");
        } else {
            uriRequest.setHeader(HEADER_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);
        synchronized (requestMap) {
            if (requestList == null) {
                requestList = Collections.synchronizedList(new LinkedList<RequestHandle>());
                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:org.soyatec.windowsazure.management.ServiceManagementRest.java

private String walkUpgradeDomain(HttpUriRequest request, int domainId, AsyncResultCallback callback) {
    // <WalkUpgradeDomain xmlns="http://schemas.microsoft.com/windowsazure">
    // <UpgradeDomain>upgrade-domain-id</UpgradeDomain>
    // </WalkUpgradeDomain>
    String template = "<WalkUpgradeDomain xmlns=\"http://schemas.microsoft.com/windowsazure\"><UpgradeDomain>{0}</UpgradeDomain></WalkUpgradeDomain>";
    request.setHeader(HeaderNames.ContentType, APPLICATION_XML);
    return sendAsyncPostRequest(request, callback, template, domainId);
}

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

/**
 * The Create Deployment operation uploads a new service package and creates
 * a new deployment on staging or production.
 * //w w w.  jav  a 2 s . co m
 * </p>
 * 
 * Note that it is possible to call Create Deployment only for a hosted
 * service that has previously been created via the Windows Azure Developer
 * Portal. You cannot upload a new hosted service via the Service Management
 * API.
 * 
 * </p>
 * 
 * The Create Deployment operation is an asynchronous operation. To
 * determine whether the management service has finished processing the
 * request, call Get Operation Status.
 * 
 * @param serviceName
 * @param deploySlotName
 * @param define
 * @return
 */
public String createDeployment(String serviceName, DeploymentSlotType deploySlotName,
        DeploymentConfiguration configuration, AsyncResultCallback callback) {
    if (serviceName == null)
        throw new IllegalArgumentException("Service name is required!");

    if (deploySlotName == null)
        throw new IllegalArgumentException("Deployment slot type is required!");

    if (configuration == null)
        throw new IllegalArgumentException("Deployment configuration is required!");

    configuration.validate();

    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(
            URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName
                    + DEPLOYMENT_SLOTS + ConstChars.Slash + deploySlotName.getLiteral().toLowerCase()),
            HttpMethod.Post);
    request.addHeader(HeaderNames.ContentType, APPLICATION_XML);
    request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28);

    String content = "";
    if (configuration.getConfigurationFileUrl() != null)
        content = readBase64(configuration.getConfigurationFileUrl());
    else if (configuration.getConfigurationFileStream() != null) {
        try {
            content = readBase64(configuration.getConfigurationFileStream().getBytes());
        } catch (IOException e) {
            throw new StorageException(e);
        }
    }

    String label = configuration.getBase64Label();
    String body = MessageFormat.format(CREATE_DEPLOYMENT_BODY, configuration.getName(),
            configuration.getPackageBlobUrl(), content, label,
            String.valueOf(configuration.isStartDeployment()),
            String.valueOf(configuration.isTreatWarningsAsError())); // configuration.getBase64ConfigurationFile()
    // 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>";

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

From source file:io.personium.core.rs.box.PersoniumEngineSvcCollectionResource.java

/**
 * relay??.//from  w w  w  . j a  v  a  2 s  .  co m
 * @param method 
 * @param uriInfo URI
 * @param path ??
 * @param headers 
 * @param is 
 * @return JAX-RS Response
 */
public Response relaycommon(String method, UriInfo uriInfo, String path, HttpHeaders headers, InputStream is) {

    String cellName = this.davRsCmp.getCell().getName();
    String boxName = this.davRsCmp.getBox().getName();
    String requestUrl = String.format("http://%s:%s/%s/%s/%s/service/%s", PersoniumUnitConfig.getEngineHost(),
            PersoniumUnitConfig.getEnginePort(), PersoniumUnitConfig.getEnginePath(), cellName, boxName, path);

    // baseUrl?
    String baseUrl = uriInfo.getBaseUri().toString();

    // ???
    HttpClient client = new DefaultHttpClient();
    HttpUriRequest req = null;
    if (method.equals(HttpMethod.POST)) {
        HttpPost post = new HttpPost(requestUrl);
        InputStreamEntity ise = new InputStreamEntity(is, -1);
        ise.setChunked(true);
        post.setEntity(ise);
        req = post;
    } else if (method.equals(HttpMethod.PUT)) {
        HttpPut put = new HttpPut(requestUrl);
        InputStreamEntity ise = new InputStreamEntity(is, -1);
        ise.setChunked(true);
        put.setEntity(ise);
        req = put;
    } else if (method.equals(HttpMethod.DELETE)) {
        HttpDelete delete = new HttpDelete(requestUrl);
        req = delete;
    } else {
        HttpGet get = new HttpGet(requestUrl);
        req = get;
    }

    req.addHeader("X-Baseurl", baseUrl);
    req.addHeader("X-Request-Uri", uriInfo.getRequestUri().toString());
    if (davCmp instanceof DavCmpFsImpl) {
        DavCmpFsImpl dcmp = (DavCmpFsImpl) davCmp;
        req.addHeader("X-Personium-Fs-Path", dcmp.getFsPath());
        req.addHeader("X-Personium-Fs-Routing-Id", dcmp.getCellId());
    }
    req.addHeader("X-Personium-Box-Schema", this.davRsCmp.getBox().getSchema());

    // ???
    MultivaluedMap<String, String> multivalueHeaders = headers.getRequestHeaders();
    for (Iterator<Entry<String, List<String>>> it = multivalueHeaders.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String key = (String) entry.getKey();
        if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            continue;
        }
        List<String> valueList = (List<String>) entry.getValue();
        for (Iterator<String> i = valueList.iterator(); i.hasNext();) {
            String value = (String) i.next();
            req.setHeader(key, value);
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("?EngineRelay " + req.getMethod() + "  " + req.getURI());
        Header[] reqHeaders = req.getAllHeaders();
        for (int i = 0; i < reqHeaders.length; i++) {
            log.debug("RelayHeader[" + reqHeaders[i].getName() + "] : " + reqHeaders[i].getValue());
        }
    }

    // Engine??
    HttpResponse objResponse = null;
    try {
        objResponse = client.execute(req);
    } catch (ClientProtocolException e) {
        throw PersoniumCoreException.ServiceCollection.SC_INVALID_HTTP_RESPONSE_ERROR;
    } catch (Exception ioe) {
        throw PersoniumCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(ioe);
    }

    // 
    ResponseBuilder res = Response.status(objResponse.getStatusLine().getStatusCode());
    Header[] headersResEngine = objResponse.getAllHeaders();
    // ?
    for (int i = 0; i < headersResEngine.length; i++) {
        // Engine????Transfer-Encoding????
        // ?MW????????Content-Length???Transfer-Encoding????
        // 2??????????????????????
        if ("Transfer-Encoding".equalsIgnoreCase(headersResEngine[i].getName())) {
            continue;
        }
        // Engine????Date????
        // Web??MW?Jetty???2?????????
        if (HttpHeaders.DATE.equalsIgnoreCase(headersResEngine[i].getName())) {
            continue;
        }
        res.header(headersResEngine[i].getName(), headersResEngine[i].getValue());
    }

    InputStream isResBody = null;

    // ?
    HttpEntity entity = objResponse.getEntity();
    if (entity != null) {
        try {
            isResBody = entity.getContent();
        } catch (IllegalStateException e) {
            throw PersoniumCoreException.ServiceCollection.SC_UNKNOWN_ERROR.reason(e);
        } catch (IOException e) {
            throw PersoniumCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(e);
        }
        final InputStream isInvariable = isResBody;
        // ??
        StreamingOutput strOutput = new StreamingOutput() {
            @Override
            public void write(final OutputStream os) throws IOException {
                int chr;
                try {
                    while ((chr = isInvariable.read()) != -1) {
                        os.write(chr);
                    }
                } finally {
                    isInvariable.close();
                }
            }
        };
        res.entity(strOutput);
    }

    // ??
    return res.build();
}

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

/**
 * The Add Certificate operation adds a certificate to the subscription.
 * http://msdn.microsoft.com/en-us/library/ee460817.aspx
 * /*from   w  w w.  j  a  v a 2s  .co  m*/
 * @param serviceName
 * @param data
 * @param format
 * @param password
 */
@Override
public void addCertificate(String serviceName, byte[] data, CertificateFormat format, String password) {
    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(
            URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName + CERTIFICATES),
            HttpMethod.Post);
    String template = "<CertificateFile xmlns=\"http://schemas.microsoft.com/windowsazure\"><Data>{0}</Data><CertificateFormat>{1}</CertificateFormat><Password>{2}</Password></CertificateFile>";
    request.setHeader(HeaderNames.ContentType, APPLICATION_XML);
    String body = MessageFormat.format(template, Base64.encode(data), format.getLiteral(),
            password == null ? "" : password);
    ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes()));
    try {
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
        if (isRequestAccepted(response)) {
            return;
        } else {
            HttpUtilities.processUnexpectedStatusCode(response);
        }
    } catch (StorageException we) {
        throw HttpUtilities.translateWebException(we);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

}

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

/**
 * The Reboot Role Instance operation requests a reboot of a role instance
 * that is running in a deployment. The Reboot Role Instance operation is an
 * asynchronous operation./*from   w ww  .  ja  v a 2 s  .com*/
 * 
 * @param serviceName
 * @param deploySlotName
 * @param roleInstanceName
 * @param callback
 * @return
 */
public String rebootRoleInstance(String serviceName, DeploymentSlotType deploySlotName, String roleInstanceName,
        AsyncResultCallback callback) {
    if (serviceName == null)
        throw new IllegalArgumentException("Service name is required!");

    if (deploySlotName == null)
        throw new IllegalArgumentException("Deployment slot type is required!");

    if (roleInstanceName == null)
        throw new IllegalArgumentException("Role instance name is required!");

    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(
            URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName
                    + DEPLOYMENT_SLOTS + ConstChars.Slash + deploySlotName.getLiteral().toLowerCase()
                    + ConstChars.Slash + ROLE_INSTANCES + ConstChars.Slash + roleInstanceName + "?comp=reboot"),
            HttpMethod.Post);
    request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28);
    return sendAsynchronousRequest(request, callback);
}

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

public String rebootRoleInstance(String serviceName, String deploymentName, String roleInstanceName,
        AsyncResultCallback callback) {/*from  w w w .  j a v a2s . c om*/
    if (serviceName == null)
        throw new IllegalArgumentException("Service name is required!");

    if (deploymentName == null)
        throw new IllegalArgumentException("Deployment name is required!");

    if (roleInstanceName == null)
        throw new IllegalArgumentException("Role instance name is required!");

    HttpUriRequest request = HttpUtilities
            .createServiceHttpRequest(
                    URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName
                            + DEPLOYMENTS + ConstChars.Slash + deploymentName + ConstChars.Slash
                            + ROLE_INSTANCES + ConstChars.Slash + roleInstanceName + "?comp=reboot"),
                    HttpMethod.Post);
    request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28);
    return sendAsynchronousRequest(request, callback);
}

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

public String reimageRoleInstance(String serviceName, String deploymentName, String roleInstanceName,
        AsyncResultCallback callback) {//from ww w .  j av  a2  s .c  om
    if (serviceName == null)
        throw new IllegalArgumentException("Service name is required!");

    if (deploymentName == null)
        throw new IllegalArgumentException("Deployment name is required!");

    if (roleInstanceName == null)
        throw new IllegalArgumentException("Role instance name is required!");

    HttpUriRequest request = HttpUtilities
            .createServiceHttpRequest(
                    URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName
                            + DEPLOYMENTS + ConstChars.Slash + deploymentName + ConstChars.Slash
                            + ROLE_INSTANCES + ConstChars.Slash + roleInstanceName + "?comp=reimage"),
                    HttpMethod.Post);
    request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28);

    return sendAsynchronousRequest(request, callback);

}

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

@Override
public String startVMRole(String serviceName, String deploymentName, String roleName,
        AsyncResultCallback callback) {/* w ww .j  a  v  a2s .com*/

    if (deploymentName == null)
        throw new IllegalArgumentException("Deployment name is required!");
    if (serviceName == null)
        throw new IllegalArgumentException("Service Name is required!");
    if (roleName == null) {
        throw new IllegalArgumentException("RoleName is requred!");
    }

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

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

    String body = START_ROLE_OPERATIONS;

    System.out.println(body);

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

}