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:com.vanda.beivandalibnetwork.utils.HttpUtils.java

/**
 * /*w w  w . ja  v a 2  s. c o  m*/
 * 
 * @param request
 * @param username
 * @param password
 * @return
 */
@TargetApi(Build.VERSION_CODES.FROYO)
public static HttpUriRequest authenticate(HttpUriRequest request, String username, String password) {
    request.addHeader(HEADER_AUTHORIZATION,
            AUTH_METHOD_BASIC + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
    return request;
}

From source file:org.simple.net.httpstacks.HttpClientStack.java

/**
 * ???Http/*from  ww  w . ja v  a  2 s .  co  m*/
 * 
 * @param request
 * @return
 */
static HttpUriRequest createHttpRequest(Request<?> request) {
    HttpUriRequest httpUriRequest = null;
    switch (request.getHttpMethod()) {
    case GET:
        httpUriRequest = new HttpGet(request.getUrl());
        break;
    case DELETE:
        httpUriRequest = new HttpDelete(request.getUrl());
        break;
    case POST: {
        httpUriRequest = new HttpPost(request.getUrl());
        httpUriRequest.addHeader(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody((HttpPost) httpUriRequest, request);
    }
        break;
    case PUT: {
        httpUriRequest = new HttpPut(request.getUrl());
        httpUriRequest.addHeader(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody((HttpPut) httpUriRequest, request);
    }
        break;
    default:
        throw new IllegalStateException("Unknown request method.");
    }

    return httpUriRequest;
}

From source file:bbd.basesimplenet.net.httpstacks.HttpClientStack.java

/**
 * ???Http//from  ww w . java2  s  . c om
 *
 * @param request
 * @return
 */
static HttpUriRequest createHttpRequest(Request<?> request) {
    HttpUriRequest httpUriRequest = null;
    switch (request.getmHttpMethod()) {
    case GET:
        httpUriRequest = new HttpGet(request.getmUrl());
        break;
    case DELETE:
        httpUriRequest = new HttpDelete(request.getmUrl());
        break;
    case POST: {
        httpUriRequest = new HttpPost(request.getmUrl());
        httpUriRequest.addHeader(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody((HttpPost) httpUriRequest, request);
    }
        break;
    case PUT: {
        httpUriRequest = new HttpPut(request.getmUrl());
        httpUriRequest.addHeader(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody((HttpPut) httpUriRequest, request);
    }
        break;
    default:
        throw new IllegalStateException("Unknown request method.");
    }

    return httpUriRequest;
}

From source file:com.betfair.application.performance.BaselinePerformanceTester.java

private static void makeRequest(HttpCallable call, String contentType, Random rnd) {
    HttpClient httpc = client.get();//from w  w  w .  j  av a2  s  .  c  o m
    if (httpc == null) {
        httpc = new DefaultHttpClient();
        client.set(httpc);
    }
    HttpCallLogEntry cle = new HttpCallLogEntry();
    int randomiser = rnd.nextInt(50);
    avgRandomiser.addAndGet(randomiser);
    HttpUriRequest method = call.getMethod(contentType, new Object[] { randomiser }, randomiser, cle);
    method.addHeader("Authority", "CoUGARUK");
    CallLogCount loggedCount = null;
    // Execute the method.
    synchronized (LOG) {
        loggedCount = LOG.get(cle);
        if (loggedCount == null) {
            loggedCount = new CallLogCount();
            LOG.put(cle, loggedCount);
        }
    }
    long nanoTime = System.nanoTime();

    InputStream is = null;

    try {

        if (TRACE_EVERY > 0 && callsMade.incrementAndGet() % TRACE_EVERY == 0) {
            method.addHeader("X-Trace-Me", "true");
        }
        loggedCount.numCalls.incrementAndGet();
        final HttpResponse httpResponse = httpc.execute(method);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        boolean failed = false;

        int expectedHTTPCode = call.expectedResult();
        if (contentType.equals(SOAP) && expectedHTTPCode != HttpStatus.SC_OK) {
            // All SOAP errors are 500.
            expectedHTTPCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        }
        if (statusCode != expectedHTTPCode) {
            System.err.println("Method failed: " + httpResponse.getStatusLine().getReasonPhrase());
            failed = true;
        }
        // Read the response body.
        is = httpResponse.getEntity().getContent();
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int b;
        while ((b = is.read()) != -1) {
            baos.write(b);
        }
        is.close();
        String result = new String(baos.toByteArray(), CHARSET);
        if (result.length() == 0) {
            System.err.println("FAILURE: Empty buffer returned");
            failed = true;
        }
        if (failed) {
            loggedCount.failures.incrementAndGet();
        }
        bytesReceived.addAndGet(baos.toByteArray().length);

        if (CHECK_LOG && NUM_THREADS == 1) {
            File logFile = new File(
                    "C:\\perforce\\se\\development\\HEAD\\cougar\\cougar-framework\\baseline\\baseline-launch\\logs\\request-Baseline.log");
            String lastLine = getLastLine(logFile);
            int tries = 0;
            while (!lastLine.contains(METHOD_NAMES.get(call.getName()))) {
                if (++tries > 5) {
                    System.err.println(
                            "LOG FAIL: Call: " + METHOD_NAMES.get(call.getName()) + ", Line: " + lastLine);
                } else {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                    }
                }
                lastLine = getLastLine(logFile);
            }
            totalLogRetries.addAndGet(tries);
        }

    } catch (Exception e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        loggedCount.failures.incrementAndGet();
    } finally {
        // Release the connection.
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                /* ignore */}
        }
        callsRemaining.decrementAndGet();

        nanoTime = System.nanoTime() - nanoTime;
        loggedCount.callTime.addAndGet(nanoTime);
    }
}

From source file:com.magnet.tools.tests.RestStepDefs.java

private static void setHttpHeaders(HttpUriRequest request, RestQueryEntry e) {
    // Set headers:
    String acceptValue;/*from w  w w .ja v  a  2  s.co m*/
    if (e.accept != null && e.accept.length() != 0) {
        acceptValue = e.accept;
    } else {
        acceptValue = "*/*";
    }

    request.addHeader(HttpHeaders.ACCEPT, acceptValue);

    String contentType;
    if (e.type != null && e.type.length() != 0) {
        contentType = e.type;
    } else {
        contentType = "*/*";
    }
    request.addHeader(HttpHeaders.CONTENT_TYPE, contentType);

    if (isStringNotEmpty(e.basicAuth)) {
        request.addHeader(HttpHeaders.AUTHORIZATION,
                "Basic " + new String(Base64.encodeBase64(e.basicAuth.getBytes())));
    }

    if (isStringNotEmpty(e.headers)) {
        String[] headers = e.headers.split(";");
        if (headers.length > 0) {
            for (String h : headers) {
                String[] kv = h.split("=");
                if (kv.length == 2) {
                    request.addHeader(kv[0], kv[1]);
                }
            }
        }
    }
}

From source file:org.dojotoolkit.zazl.internal.XMLHttpRequestUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static String xhrRequest(String shrDataString) {
    InputStream is = null;/*  w w  w . j a v  a  2s. co  m*/
    String json = null;

    try {
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "shrDataString [" + shrDataString + "]");

        Map<String, Object> xhrData = (Map<String, Object>) JSONParser.parse(new StringReader(shrDataString));
        String url = (String) xhrData.get("url");
        String method = (String) xhrData.get("method");
        List headers = (List) xhrData.get("headers");
        URL requestURL = createURL(url);
        URI uri = new URI(requestURL.toString());

        HashMap httpMethods = new HashMap(7);
        httpMethods.put("DELETE", new HttpDelete(uri));
        httpMethods.put("GET", new HttpGet(uri));
        httpMethods.put("HEAD", new HttpHead(uri));
        httpMethods.put("OPTIONS", new HttpOptions(uri));
        httpMethods.put("POST", new HttpPost(uri));
        httpMethods.put("PUT", new HttpPut(uri));
        httpMethods.put("TRACE", new HttpTrace(uri));
        HttpUriRequest request = (HttpUriRequest) httpMethods.get(method.toUpperCase());

        if (request.equals(null)) {
            throw new Error("SYNTAX_ERR");
        }

        for (Object header : headers) {
            StringTokenizer st = new StringTokenizer((String) header, ":");
            String name = st.nextToken();
            String value = st.nextToken();
            request.addHeader(name, value);
        }

        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(request);
        Map headerMap = new HashMap();

        HeaderIterator headerIter = response.headerIterator();

        while (headerIter.hasNext()) {
            Header header = headerIter.nextHeader();
            headerMap.put(header.getName(), header.getValue());
        }

        int status = response.getStatusLine().getStatusCode();
        String statusText = response.getStatusLine().toString();

        is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        StringBuffer sb = new StringBuffer();

        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        Map m = new HashMap();
        m.put("status", new Integer(status));
        m.put("statusText", statusText);
        m.put("responseText", sb.toString());
        m.put("headers", headerMap.toString());
        StringWriter w = new StringWriter();
        JSONSerializer.serialize(w, m);
        json = w.toString();
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest", "json [" + json + "]");
    } catch (Throwable e) {
        logger.logp(Level.SEVERE, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "Failed request for [" + shrDataString + "]", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    return json;
}

From source file:com.sayar.requests.impl.HttpClientRequestHandler.java

private static HttpUriRequest addHeaderParams(final HttpUriRequest request,
        final Map<String, String> headerParams) {
    // Check if the params are empty.
    if (!headerParams.isEmpty()) {
        // Iterate using the enhanced for loop synthax as the JIT will
        // optimize it away
        // See//from   w  w  w .  ja  v  a  2  s  .  c  o m
        // http://developer.android.com/guide/practices/design/performance.html#foreach
        for (final Map.Entry<String, String> entry : headerParams.entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }
    return request;
}

From source file:com.github.restdriver.serverdriver.RestServerDriver.java

private static Response doHttpRequest(ServerDriverHttpUriRequest request) {

    HttpClient httpClient = new DefaultHttpClient(RestServerDriver.ccm, RestServerDriver.httpParams);

    HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, (int) request.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpParams, (int) request.getSocketTimeout());
    HttpClientParams.setRedirecting(httpParams, false);

    if (request.getProxyHost() != null) {
        httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, request.getProxyHost());
    }//  w  ww. j  a  va  2s  .co m

    HttpUriRequest httpUriRequest = request.getHttpUriRequest();

    if (!httpUriRequest.containsHeader(USER_AGENT)) {
        httpUriRequest.addHeader(USER_AGENT, DEFAULT_USER_AGENT);
    }

    HttpResponse response;

    try {
        long startTime = System.currentTimeMillis();
        response = httpClient.execute(httpUriRequest);
        long endTime = System.currentTimeMillis();

        return new DefaultResponse(response, (endTime - startTime));

    } catch (ClientProtocolException cpe) {
        throw new RuntimeClientProtocolException(cpe);

    } catch (UnknownHostException uhe) {
        throw new RuntimeUnknownHostException(uhe);

    } catch (HttpHostConnectException hhce) {
        throw new RuntimeHttpHostConnectException(hhce);

    } catch (IOException e) {
        throw new RuntimeException("Error executing request", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

private static Map<String, String> writeOutBoundHeaders(final MultivaluedMap<String, Object> headers,
        final HttpUriRequest request) {
    Map<String, String> stringHeaders = HeaderUtils.asStringHeadersSingleValue(headers);

    for (Map.Entry<String, String> e : stringHeaders.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }//from w ww . jav  a  2 s .c  o m
    return stringHeaders;
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

private static Map<String, String> writeOutBoundHeaders(final MultivaluedMap<String, Object> headers,
        final HttpUriRequest request) {
    final Map<String, String> stringHeaders = HeaderUtils.asStringHeadersSingleValue(headers);

    for (final Map.Entry<String, String> e : stringHeaders.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }//from  ww  w .  j  a v a2  s .  co m
    return stringHeaders;
}