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

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

Introduction

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

Prototype

void addHeader(String str, String str2);

Source Link

Usage

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

/**
 * List Operating System Families/*from  w ww  .  j a  v  a2s  .  c  o m*/
 * 
 * @return a list of OperatingSystemFamily
 */
public List<OperatingSystemFamily> listOSFamilies() {
    HttpUriRequest request = HttpUtilities
            .createHttpRequest(URI.create(getBaseUrl() + OPERATING_SYSTEM_FAMILIES), HttpMethod.Get);
    request.addHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28);
    try {
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
        if (isRequestAccepted(response)) {
            return XPathQueryHelper.parseOperatingSystemFamiliesResponse(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:com.tandong.sa.aq.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {

    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }//from   ww w  . j  a  v  a2 s .  co m

    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }

    }

    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }

    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, hr);
    }

    DefaultHttpClient client = getClient();

    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }

    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    request = hr;

    if (abort) {
        throw new IOException("Aborted");
    }

    HttpResponse response = client.execute(hr, context);

    byte[] data = null;

    String redirect = url;

    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;

    HttpEntity entity = response.getEntity();

    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);

    File file = null;

    if (code < 200 || code >= 300) {

        try {

            if (entity != null) {

                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);

                error = new String(s, "UTF-8");

                AQUtility.debug("error", error);

            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }

    } else {

        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();

        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));

        OutputStream os = null;
        InputStream is = null;

        try {
            file = getPreFile();

            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }

            //AQUtility.time("copy");

            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());

            //AQUtility.timeEnd("copy", 0);

            os.flush();

            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }

        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }

    }

    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());

}

From source file:com.androidquery.callback.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {

    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }//from  w  w w .  j  av  a 2  s.co  m

    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }

    }

    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }

    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, hr);
    }

    DefaultHttpClient client = getClient();

    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }

    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    request = hr;

    if (abort) {
        throw new IOException("Aborted");
    }

    HttpResponse response = null;

    try {
        response = client.execute(hr, context);
    } catch (HttpHostConnectException e) {

        //if proxy is used, automatically retry without proxy
        if (proxy != null) {
            AQUtility.debug("proxy failed, retrying without proxy");
            hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
            response = client.execute(hr, context);
        } else {
            throw e;
        }
    }

    byte[] data = null;

    String redirect = url;

    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;

    HttpEntity entity = response.getEntity();

    File file = null;

    if (code < 200 || code >= 300) {

        InputStream is = null;

        try {

            if (entity != null) {

                is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);

                error = new String(s, "UTF-8");

                AQUtility.debug("error", error);

            }
        } catch (Exception e) {
            AQUtility.debug(e);
        } finally {
            AQUtility.close(is);
        }

    } else {

        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();

        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));

        OutputStream os = null;
        InputStream is = null;

        try {
            file = getPreFile();

            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }

            //AQUtility.time("copy");

            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());

            //AQUtility.timeEnd("copy", 0);

            os.flush();

            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }

        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }

    }

    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());

}

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

/**
 * The Regenerate Keys operation regenerates the primary or secondary access
 * key for the specified storage account.
 *//*from  w  w  w .  java  2 s  .c o  m*/
public StorageAccountKey regenerateKeys(String serviceName, KeyType type) {
    if (type == null) {
        throw new IllegalArgumentException("Key type null");
    }
    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(URI.create(
            getBaseUrl() + SERVICES_STORAGESERVICE + ConstChars.Slash + serviceName + KEYS_ACTION_REGENERATE),
            HttpMethod.Post);
    request.addHeader(HeaderNames.ContentType, MEIDA_TYPE_TEXT_XML);
    try {
        String template = "<RegenerateKeys xmlns=\"http://schemas.microsoft.com/windowsazure\"><KeyType>{0}</KeyType></RegenerateKeys>";
        String body = MessageFormat.format(template, type.getLiteral());
        ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes()));
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
        if (isRequestAccepted(response)) {
            return convertServiceToKeys(response);
        } 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 void createStorageAccount(String accountName, String label, String description, String location,
        String affinityGroup, AsyncResultCallback callback) {
    if (accountName == null)
        throw new IllegalArgumentException("Storage account name is required!");
    if (label == null)
        throw new IllegalArgumentException("Label is required!");

    if (description == null)
        description = "";

    String lc = "";
    if (location != null && location.length() > 0) {
        lc = MessageFormat.format(HOSTED_SERVICE_LOCATION, location);
        if (!isLocationExist(location))
            throw new IllegalArgumentException("Location is not exist!");
    }// ww  w  .  j  a va 2s  .  c om
    if (affinityGroup != null && affinityGroup.length() > 0) {
        if (lc.length() > 0) {
            throw new IllegalArgumentException("Specify either Location or AffinityGroup, but not both!");
        } else {
            lc = MessageFormat.format(HOSTED_SERVICE_AFFINITYGROUP, affinityGroup);
        }
    }
    HttpUriRequest request = HttpUtilities
            .createServiceHttpRequest(URI.create(getBaseUrl() + SERVICES_STORAGESERVICE), HttpMethod.Post);

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

    String base64Label = Base64.encode(label.getBytes());
    String body = MessageFormat.format(CREATE_STORAGE_SERVICE, accountName, base64Label, description, lc);
    ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes()));
    sendAsynchronousRequest(request, callback);
}

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

/**
 * The Create Hosted Service operation creates a new hosted service in
 * Windows Azure./*from   w w  w  .j a  v a 2s.  co  m*/
 * 
 * @param serviceName
 * @param configuration
 * @return
 */
public void createHostedService(String serviceName, String label, String description, String location,
        String affinityGroup) {

    if (serviceName == null)
        throw new IllegalArgumentException("Service name is required!");
    if (label == null)
        throw new IllegalArgumentException("Service label is required!");

    if (isServiceExist(serviceName))
        throw new IllegalArgumentException("Service already exist!");

    if (description == null)
        description = "";

    String lc = "";
    if (location != null && location.length() > 0) {
        lc = MessageFormat.format(HOSTED_SERVICE_LOCATION, location);
        if (!isLocationExist(location))
            throw new IllegalArgumentException("Location is not exist!");
    }
    if (affinityGroup != null && affinityGroup.length() > 0) {
        if (lc.length() > 0) {
            throw new IllegalArgumentException("Specify either Location or AffinityGroup, but not both!");
        } else {
            lc = MessageFormat.format(HOSTED_SERVICE_AFFINITYGROUP, affinityGroup);
        }
    }
    HttpUriRequest request = HttpUtilities
            .createServiceHttpRequest(URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES), HttpMethod.Post);

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

    String base64Label = Base64.encode(label.getBytes());
    String body = MessageFormat.format(CREATE_HOSTED_SERVICE, serviceName, base64Label, description, lc);
    try {
        ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes()));
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
        if (response.getStatusCode() == HttpStatus.SC_OK || response.getStatusCode() == HttpStatus.SC_CREATED) {
            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

@Override
public void updateAffinityGroup(String groupName, String label, String description) {
    if (groupName == null)
        throw new IllegalArgumentException("Group name is required!");

    if (label == null)
        throw new IllegalArgumentException("Label is required!");

    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(
            URI.create(getBaseUrl() + SERVICES_AFFINITYGROUPS + ConstChars.Slash + groupName), HttpMethod.Put);

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

    String base64Label = Base64.encode(label.getBytes());

    if (description == null)
        description = "";
    else/*from w w w.  ja v a2s  .c  om*/
        description = "<Description>" + description + "</Description>";

    String body = MessageFormat.format(UPDATE_AFFINITY_GROUP, base64Label, description);
    try {
        ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes()));
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
        if (response.getStatusCode() == HttpStatus.SC_OK) {
            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

@Override
public void updateStorageAccount(String accountName, String label, String description) {
    if (label == null && description == null)
        throw new IllegalArgumentException(
                "You must specify a value for either Label or Description, or for both.");

    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(
            URI.create(getBaseUrl() + SERVICES_STORAGESERVICE + ConstChars.Slash + accountName),
            HttpMethod.Put);//from   w w w  .java2s.com

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

    String base64Label = "";
    if (label != null)
        base64Label = "<Label>" + Base64.encode(label.getBytes()) + "</Label>";

    if (description == null)
        description = "";
    else
        description = "<Description>" + description + "</Description>";

    String body = MessageFormat.format(UPDATE_STORAGE_SERVICE, description, base64Label);
    try {
        ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes()));
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
        if (response.getStatusCode() == HttpStatus.SC_OK) {
            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 Update Hosted Service operation updates the label and/or the
 * description for a hosted service in Windows Azure.
 * /*from   w ww.j a  v  a 2 s .  c  o  m*/
 * @param serviceName
 */
public void updateHostedService(String serviceName, String label, String description) {
    if (label == null && description == null)
        throw new IllegalArgumentException(
                "You must specify a value for either Label or Description, or for both.");

    HttpUriRequest request = HttpUtilities.createServiceHttpRequest(
            URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName),
            HttpMethod.Put);

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

    String base64Label = "";
    if (label != null)
        base64Label = "<Label>" + Base64.encode(label.getBytes()) + "</Label>";

    if (description == null)
        description = "";
    else
        description = "<Description>" + description + "</Description>";

    String body = MessageFormat.format(UPDATE_HOSTED_SERVICE, base64Label, description);
    try {
        ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes()));
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
        if (response.getStatusCode() == HttpStatus.SC_OK) {
            return;
        } else {
            HttpUtilities.processUnexpectedStatusCode(response);
        }
    } catch (StorageException we) {
        throw HttpUtilities.translateWebException(we);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

}