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.jobaline.uiautomation.framework.selenium.phantomJsThreeHourTimeoutFix.HttpCommandExecutor.java

public Response execute(Command command) throws IOException {
    HttpContext context = new BasicHttpContext();

    if (command.getSessionId() == null) {
        if (QUIT.equals(command.getName())) {
            return new Response();
        }/*from  w  w w.  j  a  v a 2 s .  c  o m*/
        if (!GET_ALL_SESSIONS.equals(command.getName()) && !NEW_SESSION.equals(command.getName())) {
            throw new SessionNotFoundException("Session ID is null. Using WebDriver after calling quit()?");
        }
    }

    CommandInfo info = nameToUrl.get(command.getName());
    try {
        HttpUriRequest httpMethod = info.getMethod(remoteServer, command);

        setAcceptHeader(httpMethod);

        if (httpMethod instanceof HttpPost) {
            String payload = new BeanToJsonConverter().convert(command.getParameters());
            ((HttpPost) httpMethod).setEntity(new StringEntity(payload, "utf-8"));
            httpMethod.addHeader("Content-Type", "application/json; charset=utf-8");
        }

        // Do not allow web proxy caches to cache responses to "get" commands
        if (httpMethod instanceof HttpGet) {
            httpMethod.addHeader("Cache-Control", "no-cache");
        }

        log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true));
        HttpResponse response = fallBackExecute(context, httpMethod);
        log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false));

        response = followRedirects(client, context, response, /* redirect count */0);

        final EntityWithEncoding entityWithEncoding = new EntityWithEncoding(response.getEntity());

        return createResponse(response, context, entityWithEncoding);
    } catch (UnsupportedCommandException e) {
        if (e.getMessage() == null || "".equals(e.getMessage())) {
            throw new UnsupportedOperationException(
                    "No information from server. Command name was: " + command.getName(), e.getCause());
        }
        throw e;
    }
}

From source file:com.xiao.smartband.http.AsyncHttpClient.java

private void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }//from  w  w w .  j a va 2  s .  c  om
    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?
    }
}

From source file:com.ytrain.mutrain.utils.asynchttp.AsyncHttpClient.java

protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }/*from  w ww. j a  va 2s  . co  m*/

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

    if (context != null) {

        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));

    }
}

From source file:nl.opengeogroep.filesetsync.client.FilesetSyncer.java

private void retrieveFilesetList() throws IOException {

    final boolean cachedFileList = state.getFileListDate() != null
            && state.getFileListRemotePath().equals(fs.getRemote())
            && (!fs.isHash() || state.isFileListHashed()) && SyncJobState.haveCachedFileList(fs.getName());

    String s = "Retrieving file list";
    if (cachedFileList) {
        s += String.format(" (last file list cached at %s)", FormatUtil.dateToString(state.getFileListDate()));
    }//from  w  w w  . ja v a2s . c  o  m
    action(s);

    try (CloseableHttpClient httpClient = HttpClientUtil.get()) {
        HttpUriRequest get = RequestBuilder.get().setUri(serverUrl + "list/" + fs.getRemote())
                .addParameter("hash", fs.isHash() + "").addParameter("regexp", fs.getRegexp()).build();
        if (cachedFileList) {
            get.addHeader(HttpHeaders.IF_MODIFIED_SINCE, HttpUtil.formatDate(state.getFileListDate()));
        }
        addExtraHeaders(get);
        // Request poorly encoded text format
        get.addHeader(HttpHeaders.ACCEPT, "text/plain");

        ResponseHandler<List<FileRecord>> rh = new ResponseHandler<List<FileRecord>>() {
            @Override
            public List handleResponse(HttpResponse hr) throws ClientProtocolException, IOException {
                log.info("< " + hr.getStatusLine());

                int status = hr.getStatusLine().getStatusCode();
                if (status == SC_NOT_MODIFIED) {
                    return null;
                } else if (status >= SC_OK && status < 300) {
                    HttpEntity entity = hr.getEntity();
                    if (entity == null) {
                        throw new ClientProtocolException("No response entity, invalid server URL?");
                    }
                    try (InputStream in = entity.getContent()) {
                        return Protocol.decodeFilelist(in);
                    }
                } else {
                    if (log.isTraceEnabled()) {
                        String entity = hr.getEntity() == null ? null : EntityUtils.toString(hr.getEntity());
                        log.trace("Response body: " + entity);
                    } else {
                        EntityUtils.consumeQuietly(hr.getEntity());
                    }
                    throw new ClientProtocolException("Server error: " + hr.getStatusLine());
                }
            }
        };

        log.info("> " + get.getRequestLine());
        fileList = httpClient.execute(get, rh);

        if (fileList == null) {
            log.info("Cached file list is up-to-date");

            fileList = SyncJobState.readCachedFileList(fs.getName());
        } else {
            log.info("Filelist returned " + fileList.size() + " files");

            /* Calculate last modified client-side, requires less server
             * memory
             */

            long lastModified = -1;
            for (FileRecord fr : fileList) {
                lastModified = Math.max(lastModified, fr.getLastModified());
            }
            if (lastModified != -1) {
                state.setFileListRemotePath(fs.getRemote());
                state.setFileListDate(new Date(lastModified));
                state.setFileListHashed(fs.isHash());
                SyncJobState.writeCachedFileList(fs.getName(), fileList);
                SyncJobStatePersistence.persist();
            }
        }
    }
}

From source file:eu.nullbyte.android.urllib.Urllib.java

public HttpResponse openAsHttpResponse(String url, HttpEntity entity, HttpMethod method)
        throws ClientProtocolException, IOException {
    this.currentURI = url;
    HttpResponse response;/*w  w  w.  ja  va  2  s . c o m*/
    String[] headerKeys = (String[]) this.headers.keySet().toArray(new String[headers.size()]);
    String[] headerVals = (String[]) this.headers.values().toArray(new String[headers.size()]);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    HttpUriRequest request;
    switch (method) {
    case GET:
        request = new HttpGet(url);
        break;
    case POST:
        request = new HttpPost(url);
        ((HttpPost) request).setEntity(entity);
        break;
    case PUT:
        request = new HttpPut(url);
        ((HttpPut) request).setEntity(entity);
        break;
    default:
        request = new HttpGet(url);
    }
    if (userAgent != null)
        request.addHeader("User-Agent", userAgent);

    for (int i = 0; i < headerKeys.length; i++) {
        request.addHeader(headerKeys[i], headerVals[i]);
    }

    response = httpclient.execute(request, mHttpContext);

    //HttpUriRequest currentReq = (HttpUriRequest)mHttpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    //HttpHost currentHost = (HttpHost)mHttpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    //this.currentURI = currentHost.toURI() + currentReq.getURI();
    this.currentURI = request.getURI().toString();

    return response;
}

From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java

/**
 * ?.//from  w  w w .  jav a 2 s .c  o m
 * @param req 
 * @param contentType 
 * @param accept Accept
 * @param etag Etag
 */
protected final void makeCommonHeaders(final HttpUriRequest req, final String contentType, final String accept,
        final String etag) {
    /*
     * String token = accessor.getAccessToken(); if (!token.isEmpty()) { req.setHeader("Authorization",
     * "Token token=\"" + token + "\""); } DaoConfig config = accessor.getDaoConfig(); String version =
     * config.getDcVersion(); if (!"".equals(version)) { req.setHeader("X-Tritium-Version", version); }
     */
    if (contentType != null) {
        req.addHeader("Content-Type", contentType);
    }
    if (accept != null) {
        req.addHeader("Accept", accept);
    }
    if (etag != null) {
        req.addHeader("If-Match", etag);
    }
}

From source file:cn.xdf.thinkutils.http2.AsyncHttpClient.java

protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }//from  ww  w  . j  a v a 2  s .  c om

    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?
    }

}

From source file:com.frand.easyandroid.http.FFHttpClient.java

protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, FFHttpRespHandler responseHandler, Context context, int reqTag, String reqUrl) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }/*from w ww  . ja  v  a2  s . c  o  m*/

    Future<?> request = threadPool
            .submit(new FFHttpRequest(client, httpContext, uriRequest, responseHandler, reqTag, reqUrl));
    if (context != null) {
        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));
    }
}

From source file:com.akop.bach.parser.Parser.java

protected String getResponse(HttpUriRequest request, List<NameValuePair> inputs)
        throws IOException, ParserException {
    if (!request.containsHeader("Accept"))
        request.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
    if (!request.containsHeader("Accept-Charset"))
        request.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

    if (App.getConfig().logToConsole())
        App.logv("Parser: Fetching %s", request.getURI());

    long started = System.currentTimeMillis();

    initRequest(request);/*from  w  w  w. j a  v  a  2s.  com*/

    try {
        synchronized (mHttpClient) {
            HttpContext context = new BasicHttpContext();

            StringBuilder log = null;

            if (App.getConfig().logHttp()) {
                log = new StringBuilder();

                log.append(String.format("URL: %s\n", request.getURI()));

                log.append("Headers: \n");
                for (Header h : request.getAllHeaders())
                    log.append(String.format("  '%s': '%s'\n", h.getName(), h.getValue()));

                log.append("Cookies: \n");
                for (Cookie c : mHttpClient.getCookieStore().getCookies())
                    log.append(String.format("  '%s': '%s'\n", c.getName(), c.getValue()));

                log.append("Query Elements: \n");

                if (inputs != null) {
                    for (NameValuePair p : inputs)
                        log.append(String.format("  '%s': '%s'\n", p.getName(), p.getValue()));
                } else {
                    log.append("  [empty]\n");
                }
            }

            try {
                mLastResponse = mHttpClient.execute(request, context);
            } catch (SocketTimeoutException e) {
                throw new ParserException(mContext, R.string.error_timed_out);
            }

            try {
                if (mLastResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(ExecutionContext.HTTP_REQUEST);
                    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                    this.mLastUrl = currentHost.toURI() + currentReq.getURI();
                }
            } catch (Exception e) {
                if (App.getConfig().logToConsole()) {
                    App.logv("Unable to get last URL - see stack:");
                    e.printStackTrace();
                }

                this.mLastUrl = null;
            }

            HttpEntity entity = mLastResponse.getEntity();

            if (entity == null)
                return null;

            InputStream stream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream), 10000);
            StringBuilder builder = new StringBuilder(10000);

            try {
                int read;
                char[] buffer = new char[1000];

                while ((read = reader.read(buffer)) >= 0)
                    builder.append(buffer, 0, read);
            } catch (OutOfMemoryError e) {
                return null;
            }

            stream.close();
            entity.consumeContent();

            String response;

            try {
                response = builder.toString();
            } catch (OutOfMemoryError e) {
                if (App.getConfig().logToConsole())
                    e.printStackTrace();

                return null;
            }

            if (App.getConfig().logHttp()) {
                log.append(String.format("\nResponse: \n%s\n", response));

                writeToFile(
                        generateDatedFilename(
                                "http-log-" + request.getURI().toString().replaceAll("[^A-Za-z0-9]", "_")),
                        log.toString());
            }

            return preparseResponse(response);
        }
    } finally {
        if (App.getConfig().logToConsole())
            displayTimeTaken("Parser: Fetch took", started);
    }
}