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.library.loopj.android.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  .java  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) {
        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:com.example.administrator.newsdaily.model.httpclient.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
 *//*from  ww  w  .  jav  a2 s  .  co m*/
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<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:com.rae.core.http.async.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
 *///from  ww  w.  ja  v a  2s  . co  m
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 = newAsyncHttpRequest(client, httpContext, uriRequest, contentType,
            responseHandler, context);
    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<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.jets3t.service.impl.rest.httpclient.RestS3Service.java

/**
 * Creates an {@link HttpUriRequest} object to handle a particular connection method.
 *
 * @param method//from w ww.  ja  va 2s. com
 * the HTTP method/connection-type to use, must be one of: PUT, HEAD, GET, DELETE
 * @param bucketName
 * the bucket's name
 * @param objectKey
 * the object's key name, may be null if the operation is on a bucket only.
 * @return
 * the HTTP method object used to perform the request
 *
 * @throws org.jets3t.service.S3ServiceException
 */
@Override
protected HttpUriRequest setupConnection(HTTP_METHOD method, String bucketName, String objectKey,
        Map<String, String> requestParameters) throws S3ServiceException {
    HttpUriRequest httpMethod;
    try {
        httpMethod = super.setupConnection(method, bucketName, objectKey, requestParameters);
    } catch (ServiceException se) {
        throw new S3ServiceException(se);
    }

    // Set DevPay request headers.
    if (getDevPayUserToken() != null || getDevPayProductToken() != null) {
        // DevPay tokens have been provided, include these with the request.
        if (getDevPayProductToken() != null) {
            String securityToken = getDevPayUserToken() + "," + getDevPayProductToken();
            httpMethod.setHeader(Constants.AMZ_SECURITY_TOKEN, securityToken);
            if (log.isDebugEnabled()) {
                log.debug("Including DevPay user and product tokens in request: " + Constants.AMZ_SECURITY_TOKEN
                        + "=" + securityToken);
            }
        } else {
            httpMethod.setHeader(Constants.AMZ_SECURITY_TOKEN, getDevPayUserToken());
            if (log.isDebugEnabled()) {
                log.debug("Including DevPay user token in request: " + Constants.AMZ_SECURITY_TOKEN + "="
                        + getDevPayUserToken());
            }
        }
    }

    // Set the session token from Temporary Security (Session) Credentials
    // NOTE: a session token will override any DevPay credential values set above.
    if (this.credentials instanceof AWSSessionCredentials) {
        String sessionToken = ((AWSSessionCredentials) this.credentials).getSessionToken();
        httpMethod.setHeader(Constants.AMZ_SECURITY_TOKEN, sessionToken);
        if (log.isDebugEnabled()) {
            log.debug("Including AWS session token in request: " + Constants.AMZ_SECURITY_TOKEN + "="
                    + sessionToken);
        }
    }

    // Set Requester Pays header to allow access to these buckets.
    if (this.isRequesterPaysEnabled()) {
        String[] requesterPaysHeaderAndValue = Constants.REQUESTER_PAYS_BUCKET_FLAG.split("=");
        httpMethod.setHeader(requesterPaysHeaderAndValue[0], requesterPaysHeaderAndValue[1]);
        if (log.isDebugEnabled()) {
            log.debug("Including Requester Pays header in request: " + Constants.REQUESTER_PAYS_BUCKET_FLAG);
        }
    }

    return httpMethod;
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

/**
 * public for unit test, not to be used otherwise
 *//*from   w  ww  .j a va 2  s .c  o m*/
public void execute(HttpUriRequest httpUriRequest, ContentType contentType,
        FutureCallback<HttpResponse> callback) {

    // add accept header when its not a form or multipart
    final String contentTypeString = contentType.toString();
    if (!ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType())
            && !contentType.getMimeType().startsWith(MULTIPART_MIME_TYPE)) {
        // otherwise accept what is being sent
        httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentTypeString);
    }
    // is something being sent?
    if (httpUriRequest instanceof HttpEntityEnclosingRequestBase
            && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
        httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    }

    // set user specified custom headers
    if (httpHeaders != null && !httpHeaders.isEmpty()) {
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpUriRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // add client protocol version if not specified
    if (!httpUriRequest.containsHeader(ODataHttpHeaders.DATASERVICEVERSION)) {
        httpUriRequest.addHeader(ODataHttpHeaders.DATASERVICEVERSION, ODataServiceVersion.V20);
    }
    if (!httpUriRequest.containsHeader(MAX_DATA_SERVICE_VERSION)) {
        httpUriRequest.addHeader(MAX_DATA_SERVICE_VERSION, ODataServiceVersion.V30);
    }

    // execute request
    client.execute(httpUriRequest, callback);
}

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

/**
 * The Get Deployment operation get the deployment with the request.
 * /*from w  w  w  .  j a v a2  s.c  o m*/
 * @param request
 * @return
 */
private Deployment getDeployment(HttpUriRequest request) {
    try {
        request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2011_06_01);
        HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());

        if (isRequestAccepted(response)) {
            return XPathQueryHelper.parseDeploymentResponse(response.getStream());
        } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return null;
        } else {
            HttpUtilities.processUnexpectedStatusCode(response);
        }
    } catch (StorageException we) {
        throw HttpUtilities.translateWebException(we);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return null;
}

From source file:com.iflytek.iFramework.http.asynhttp.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
 *///from  ww w . j  av a 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) {
        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) {
        // Add request to request map
        List<RequestHandle> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = 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:com.android.yijiang.kzx.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
 *///from   w w  w . j a  v a2  s .  com
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(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) {
        // 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.openestate.is24.restapi.hc43.HttpComponents43Client.java

@Override
protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input,
        String fileName, String mimeType) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;/*from  ww w  .  j a va  2 s  .  c o  m*/
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");
    xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml)
            : null;

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntityBuilder b = MultipartEntityBuilder.create();

    // add xml part to the multipart entity
    if (xml != null) {
        //InputStreamBody xmlPart = new InputStreamBody(
        //  new ByteArrayInputStream( xml.getBytes( getEncoding() ) ),
        //  ContentType.parse( "application/xml" ),
        //  "body.xml" );
        //b.addPart( "metadata", xmlPart );
        b.addTextBody("metadata", xml, ContentType.create("application/xml", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        mimeType = StringUtils.trimToNull(mimeType);
        if (mimeType == null)
            mimeType = "application/octet-stream";

        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";

        //InputStreamBody filePart = new InputStreamBody(
        //  input, ContentType.create( mimeType ), fileName );
        //b.addPart( "attachment", filePart );
        b.addBinaryBody("attachment", input, ContentType.create(mimeType), fileName);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept", "application/xml");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    getAuthConsumer().sign(request);

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}

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

@Override
public List<SubscriptionOperation> listSubscriptionOperations(String startTimeFrame, String endTimeFrame,
        ObjectIdFilter filter, OperationState operationStatus, int limit) {
    if (startTimeFrame == null)
        throw new IllegalArgumentException("startTimeFrame is required!");
    if (!validateTimeFormat(startTimeFrame))
        throw new IllegalArgumentException(
                "The time specified for parameter startTimeFrame is invalid. Accepted formats are: [4DigitYear]-[2DigitMonth]-[2DigitDay]  or [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitHour]:[2DigitMinute]:2DigitSecond]Z or [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitMinute]:[2DigitSecond]:[7DigitsOfPrecision]Z .");

    if (endTimeFrame == null)
        throw new IllegalArgumentException("endTimeFrame is required!");
    if (!validateTimeFormat(endTimeFrame))
        throw new IllegalArgumentException(
                "The time specified for parameter endTimeFrame is invalid. Accepted formats are: [4DigitYear]-[2DigitMonth]-[2DigitDay]  or [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitHour]:[2DigitMinute]:2DigitSecond]Z or [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitMinute]:[2DigitSecond]:[7DigitsOfPrecision]Z .");

    String url = getBaseUrl() + "/operations?StartTime=" + startTimeFrame + "&EndTime=" + endTimeFrame;

    if (filter != null) {
        url += "&ObjectIdFilter==/" + this.getSubscriptionId() + filter.getFilter();
    }/* w w  w .  j a  v a 2  s . c  o m*/
    if (operationStatus != null) {
        url += "&OperationResultFilter=" + operationStatus.getLiteral();
    }

    String continuationToken = null;
    List<SubscriptionOperation> result = new ArrayList<SubscriptionOperation>();
    do {
        String token = continuationToken == null ? "" : "&ContinuationToken=" + continuationToken;
        HttpUriRequest request = HttpUtilities.createServiceHttpRequest(URI.create(url + token),
                HttpMethod.Get);
        request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2011_06_01);

        try {
            HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory());
            if (isRequestAccepted(response)) {
                continuationToken = parseSubscriptionOperation(response, result);
            } else {
                HttpUtilities.processUnexpectedStatusCode(response);
            }
        } catch (StorageException we) {
            throw HttpUtilities.translateWebException(we);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        if (limit >= 0 && result.size() >= limit)
            break;
    } while (continuationToken != null);

    if (limit >= 0 && result.size() > limit)
        return result.subList(0, limit);
    else
        return result;
}