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:czd.lib.network.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. jav  a2 s .  c  om
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    if (responseHandler instanceof RangeFileAsyncHttpResponseHandler)
        ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest);
    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleAPITalker.java

/**
 * Returns an object if all went well. Returns null if a conflict was
 * detected. If the list has deleted set to 1, will call the server and
 * delete the list instead of updating it.
 * //from ww  w  .  java 2  s.  c  o m
 * @throws IOException
 * @throws PreconditionException
 * @throws JSONException
 * @throws ClientProtocolException
 */
public GoogleTaskList uploadList(final GoogleTaskList list)
        throws IOException, PreconditionException, JSONException {
    final HttpUriRequest httppost;
    if (list.remoteId != null) {
        //Log.d(TAG, "ID is not NULL!! " + ListURL(list.remoteId));
        if (list.isDeleted()) {
            httppost = new HttpDelete(ListURL(list.remoteId));
        } else {
            httppost = new HttpPost(ListURL(list.remoteId));
            // apache does not include PATCH requests, but we can force a
            // post to be a PATCH request
            httppost.setHeader("X-HTTP-Method-Override", "PATCH");
        }
    } else {
        httppost = new HttpPost(InsertLists());
        // list.didRemoteInsert = true; // Need this later
    }
    setAuthHeader(httppost);
    AndroidHttpClient.modifyRequestToAcceptGzipResponse(httppost);

    // Log.d(TAG, httppost.getRequestLine().toString());
    // for (Header header : httppost.getAllHeaders()) {
    // Log.d(TAG, header.getName() + ": " + header.getValue());
    // }

    if (!list.isDeleted()) {
        setPostBody(httppost, list);
    }

    String stringResponse = parseResponse(client.execute(httppost));

    // If we deleted the note, we will get an empty response. Return the
    // same element back.
    if (list.isDeleted()) {
        Log.d(TAG, "deleted and Stringresponse: " + stringResponse);
    } else {
        JSONObject jsonResponse = new JSONObject(stringResponse);

        // Log.d(TAG, jsonResponse.toString());

        // Will return a list, containing id and etag. always update
        // fields
        // list.etag = jsonResponse.getString("etag");
        list.remoteId = jsonResponse.getString("id");
        list.title = jsonResponse.getString("title");
        try {
            list.updated = RFC3339Date.parseRFC3339Date(jsonResponse.getString("updated")).getTime();
        } catch (Exception e) {
            list.updated = 0L;
        }
    }

    return list;
}

From source file:org.apache.asterix.test.common.TestExecutor.java

private HttpUriRequest constructPostMethod(URI uri, OutputFormat fmt, List<CompilationUnit.Parameter> params) {
    HttpUriRequest method = constructPostMethod(uri, params);
    // Set accepted output response type
    method.setHeader("Accept", fmt.mimeType());
    return method;
}

From source file:org.apache.asterix.test.common.TestExecutor.java

private HttpUriRequest constructGetMethod(URI endpoint, OutputFormat fmt,
        List<CompilationUnit.Parameter> params) {
    HttpUriRequest method = constructGetMethod(endpoint, params);
    // Set accepted output response type
    method.setHeader("Accept", fmt.mimeType());
    return method;
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

protected HttpUriRequest getHttpUriRequest(String requestMethod, String url) throws IOException {

    HttpUriRequest request = null;

    try {/* w  w w.  jav  a2 s .com*/
        URI uri = new URI(url);
        // GET or POST
        if (requestMethod.equalsIgnoreCase("get")) {
            request = new HttpGet(uri);
        } else {
            request = new HttpPost(uri);
        }

        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setHeader("Content-Language", "en-US");
        request.setHeader("Authorization", "Bearer " + sessionToken);

        request.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        request.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        request.setHeader("Expires", "0"); // Proxies.

    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    return request;
}

From source file:org.apache.asterix.test.common.TestExecutor.java

public InputStream executeQuery(String str, OutputFormat fmt, URI uri, List<CompilationUnit.Parameter> params)
        throws Exception {
    HttpUriRequest method = constructHttpMethod(str, uri, "query", false, params);
    // Set accepted output response type
    method.setHeader("Accept", fmt.mimeType());
    HttpResponse response = executeAndCheckHttpRequest(method);
    return response.getEntity().getContent();
}

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private void completeRestMethodBuild(HttpUriRequest method,
        CougarMessageContentTypeEnum responseContentTypeEnum,
        CougarMessageContentTypeEnum requestContentTypeEnum, String postQuery, Map<String, String> headerParams,
        String authority, Map<String, String> authCredentials, String altUrl,
        Map<String, String> acceptProtocols, String ipAddress) {

    String contentType = selectContent(requestContentTypeEnum);
    if (!"".equals(contentType)) {
        method.setHeader("Content-Type", contentType);
    }//www.j a v  a  2s  .  co  m

    method.setHeader("User-Agent", "java/socket");

    String accept = selectAccept(responseContentTypeEnum, acceptProtocols);
    method.setHeader("Accept", accept);

    // No need to set this header any more as it is set by the new http client version
    /*if ((postQuery != null) && (!postQuery.equalsIgnoreCase(""))) {
       Integer contentLength = postQuery.length();
       method.setHeader("Content-Length", contentLength.toString());
    }*/

    if (headerParams != null) {
        for (Map.Entry<String, String> entry : headerParams.entrySet()) {
            String headerParamValue = entry.getValue();
            String key = entry.getKey();
            method.setHeader(key, headerParamValue);
            //      logger.LogBetfairDebugEntry("Rest request header param added: '"
            //                  + key + ":" + headerParamValue + "'");
        }
    }

    if (authority != null) {
        method.setHeader("X-Authentication", authority);
    }
    if (authCredentials != null) {
        if ("".equals(altUrl)) {
            method.setHeader("X-Token-Username", authCredentials.get("Username"));
            method.setHeader("X-Token-Password", authCredentials.get("Password"));
        } else {
            method.setHeader("X-AltToken-Username", authCredentials.get("Username"));
            method.setHeader("X-AltToken-Password", authCredentials.get("Password"));
        }

    }

    if (ipAddress == null) {
        method.setHeader("X-Forwarded-For", null);
    } else if (!ipAddress.trim().equalsIgnoreCase("DO NOT INCLUDE")) {
        method.setHeader("X-Forwarded-For", ipAddress);
    }

    //logger.LogBetfairDebugEntry("Rest request postString: '"
    //      + postQuery + "'");
}

From source file:org.apache.asterix.test.common.TestExecutor.java

protected InputStream executeQueryService(String str, OutputFormat fmt, URI uri,
        List<CompilationUnit.Parameter> params, boolean jsonEncoded, boolean cancellable) throws Exception {
    final List<CompilationUnit.Parameter> newParams = upsertParam(params, "format", fmt.mimeType());
    HttpUriRequest method = jsonEncoded ? constructPostMethodJson(str, uri, "statement", newParams)
            : constructPostMethodUrl(str, uri, "statement", newParams);
    // Set accepted output response type
    method.setHeader("Accept", OutputFormat.CLEAN_JSON.mimeType());
    HttpResponse response = executeHttpRequest(method);
    return response.getEntity().getContent();
}

From source file:io.personium.jersey.engine.test.ScriptTest.java

/**
 * ????????????.//from   ww  w.  j  av  a 2  s  . c  o  m
 */
@Test
public final void serviceJapanese() {
    String url;
    String testSrc = "japanese.js";
    HttpUriRequest req = null;
    try {
        if (isServiceTest) {
            // ? Dav?put
            putScript(testSrc, "test.js");
            url = requestUrl();
        } else {
            url = requestUrl(testSrc);
        }
        // ?
        req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build();
        req.setHeader(KEY_HEADER_BASEURL, baseUrl);
        String version = getVersion();
        if (version != null && !(version.equals(""))) {
            req.setHeader("X-Personium-Version", version);
        }

        HttpResponse objResponse;
        objResponse = httpClient.execute(req);
        PersoniumResponse dcRes = new PersoniumResponse(objResponse);

        assertEquals(HttpStatus.SC_OK, dcRes.getStatusCode());
        assertEquals("??", dcRes.bodyAsString());
    } catch (DaoException e) {
        fail(e.getMessage());
    } catch (ClientProtocolException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (isServiceTest) {
            // ?Dav?del
            try {
                testSvcCol.del("test.js");
            } catch (DaoException e) {
                fail(e.getMessage());
            }
        }
    }
}