Java 类org.apache.http.HttpRequest 实例源码

项目:Reer    文件:AlwaysRedirectRedirectStrategy.java   
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    URI uri = this.getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        return this.copyEntity(new HttpPost(uri), request);
    } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
        return this.copyEntity(new HttpPut(uri), request);
    } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
        return new HttpDelete(uri);
    } else if (method.equalsIgnoreCase(HttpTrace.METHOD_NAME)) {
        return new HttpTrace(uri);
    } else if (method.equalsIgnoreCase(HttpOptions.METHOD_NAME)) {
        return new HttpOptions(uri);
    } else if (method.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
        return this.copyEntity(new HttpPatch(uri), request);
    } else {
        return new HttpGet(uri);
    }
}
项目:uavstack    文件:ApacheHttpClientAdapter.java   
@Override
public void afterPreCap(InvokeChainContext context, Object[] args) {

    if (args.length < 2) {
        return;
    }

    /**
     * after precap the client's span is created, set the span meta into http request header
     */
    String url = (String) context.get(InvokeChainConstants.CLIENT_SPAN_THREADLOCAL_STOREKEY);

    Span span = this.spanFactory.getSpanFromContext(url);

    String spanMeta = this.spanFactory.getSpanMeta(span);

    HttpRequest request = (HttpRequest) args[1];

    request.removeHeaders(InvokeChainConstants.PARAM_HTTPHEAD_SPANINFO);
    request.addHeader(InvokeChainConstants.PARAM_HTTPHEAD_SPANINFO, spanMeta);

    handleSlowOperSupporter(request, span, context);
}
项目:allure-java    文件:AllureHttpClientRequest.java   
@Override
public void process(final HttpRequest request,
                    final HttpContext context) throws HttpException, IOException {
    final HttpRequestAttachment.Builder builder = create("Request", request.getRequestLine().getUri())
            .withMethod(request.getRequestLine().getMethod());

    Stream.of(request.getAllHeaders())
            .forEach(header -> builder.withHeader(header.getName(), header.getValue()));

    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        entity.writeTo(os);

        final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
        builder.withBody(body);
    }

    final HttpRequestAttachment requestAttachment = builder.build();
    processor.addAttachment(requestAttachment, renderer);
}
项目:dhus-core    文件:TestInterruptibleHttpClient.java   
/**
 * Starts the HTTP server.
 *
 * @return the listening port.
 */
static int start () throws IOException
{

   server = ServerBootstrap.bootstrap ().registerHandler ("*",
         new HttpRequestHandler ()
         {

            @Override
            public void handle (HttpRequest request, HttpResponse response,
                  HttpContext context)
                  throws HttpException, IOException
            {

               response.setStatusCode (HttpStatus.SC_OK);
               response.setEntity (new StringEntity ("0123456789"));
            }
         })
         .create ();
   server.start ();

   return server.getLocalPort ();
}
项目:HttpClientMock    文件:HttpClientMock.java   
@Override
protected CloseableHttpResponse doExecute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException {
    synchronized (rulesUnderConstruction) {
        for (RuleBuilder ruleBuilder : rulesUnderConstruction) {
            rules.add(ruleBuilder.toRule());
        }
        rulesUnderConstruction.clear();
    }
    Request request = new Request(httpHost, httpRequest, httpContext);
    requests.add(request);
    Rule rule = rules.stream()
            .filter(r -> r.matches(httpHost, httpRequest, httpContext))
            .reduce((a, b) -> b)
            .orElse(NOT_FOUND);
    HttpResponse response = rule.nextResponse(request);
    return new HttpResponseProxy(response);
}
项目:lams    文件:DefaultRedirectHandler.java   
public boolean isRedirectRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }

    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        HttpRequest request = (HttpRequest) context.getAttribute(
                ExecutionContext.HTTP_REQUEST);
        String method = request.getRequestLine().getMethod();
        return method.equalsIgnoreCase(HttpGet.METHOD_NAME)
            || method.equalsIgnoreCase(HttpHead.METHOD_NAME);
    case HttpStatus.SC_SEE_OTHER:
        return true;
    default:
        return false;
    } //end of switch
}
项目:aws-xray-sdk-java    文件:TracedHttpClient.java   
@Override
public CloseableHttpResponse execute(
        final HttpHost target,
        final HttpRequest request,
        final HttpContext context) throws IOException, ClientProtocolException {
    Subsegment subsegment = recorder.beginSubsegment(target.getHostName());
    return wrapHttpSupplier(subsegment, () -> {
        if (null != subsegment) {
            TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request));
        }
        CloseableHttpResponse response = wrappedClient.execute(target, request, context);
        if (null != subsegment) {
            TracedResponseHandler.addResponseInformation(subsegment, response);
        }
        return response;
    });
}
项目:boohee_v5.6    文件:AsyncHttpClient$1.java   
public void process(HttpRequest request, HttpContext context) {
    if (!request.containsHeader(AsyncHttpClient.HEADER_ACCEPT_ENCODING)) {
        request.addHeader(AsyncHttpClient.HEADER_ACCEPT_ENCODING, AsyncHttpClient
                .ENCODING_GZIP);
    }
    for (String header : AsyncHttpClient.access$000(this.this$0).keySet()) {
        if (request.containsHeader(header)) {
            Header overwritten = request.getFirstHeader(header);
            Log.d(AsyncHttpClient.LOG_TAG, String.format("Headers were overwritten! (%s | %s)" +
                    " overwrites (%s | %s)", new Object[]{header, AsyncHttpClient.access$000
                    (this.this$0).get(header), overwritten.getName(), overwritten.getValue()}));
            request.removeHeader(overwritten);
        }
        request.addHeader(header, (String) AsyncHttpClient.access$000(this.this$0).get(header));
    }
}
项目:crawler    文件:CustomRedirectStrategy.java   
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if ("post".equalsIgnoreCase(method)) {
        try {
            HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) request;
            httpRequestWrapper.setURI(uri);
            httpRequestWrapper.removeHeaders("Content-Length");
            return httpRequestWrapper;
        } catch (Exception e) {
            logger.error("强转为HttpRequestWrapper出错");
        }
        return new HttpPost(uri);
    } else {
        return new HttpGet(uri);
    }
}
项目:lams    文件:BasicScheme.java   
/**
 * Produces basic authorization header for the given set of {@link Credentials}.
 *
 * @param credentials The set of credentials to be used for authentication
 * @param request The request being authenticated
 * @throws InvalidCredentialsException if authentication credentials are not
 *   valid or not applicable for this authentication scheme
 * @throws AuthenticationException if authorization string cannot
 *   be generated due to an authentication failure
 *
 * @return a basic authorization string
 */
@Override
public Header authenticate(
        final Credentials credentials,
        final HttpRequest request,
        final HttpContext context) throws AuthenticationException {

    if (credentials == null) {
        throw new IllegalArgumentException("Credentials may not be null");
    }
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }

    String charset = AuthParams.getCredentialCharset(request.getParams());
    return authenticate(credentials, charset, isProxy());
}
项目:java-elasticsearch-client    文件:TracingHttpClientConfigCallback.java   
/**
 * Extract context from headers or from active Span
 *
 * @param request http request
 * @return extracted context
 */
private SpanContext extract(HttpRequest request) {
  SpanContext spanContext = tracer.extract(Format.Builtin.HTTP_HEADERS,
      new HttpTextMapExtractAdapter(request));

  if (spanContext != null) {
    return spanContext;
  }

  Span span = tracer.activeSpan();
  if (span != null) {
    return span.context();
  }

  return null;
}
项目:lams    文件:DefaultRequestDirector.java   
/**
 * Creates the CONNECT request for tunnelling.
 * Called by {@link #createTunnelToTarget createTunnelToTarget}.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  the CONNECT request for tunnelling
 */
protected HttpRequest createConnectRequest(HttpRoute route,
                                           HttpContext context) {
    // see RFC 2817, section 5.2 and
    // INTERNET-DRAFT: Tunneling TCP based protocols through
    // Web proxy servers

    HttpHost target = route.getTargetHost();

    String host = target.getHostName();
    int port = target.getPort();
    if (port < 0) {
        Scheme scheme = connManager.getSchemeRegistry().
            getScheme(target.getSchemeName());
        port = scheme.getDefaultPort();
    }

    StringBuilder buffer = new StringBuilder(host.length() + 6);
    buffer.append(host);
    buffer.append(':');
    buffer.append(Integer.toString(port));

    String authority = buffer.toString();
    ProtocolVersion ver = HttpProtocolParams.getVersion(params);
    HttpRequest req = new BasicHttpRequest
        ("CONNECT", authority, ver);

    return req;
}
项目:lams    文件:DefaultHttpRequestRetryHandler.java   
/**
 * @since 4.2
 */
protected boolean requestIsAborted(final HttpRequest request) {
    HttpRequest req = request;
    if (request instanceof RequestWrapper) { // does not forward request to original
        req = ((RequestWrapper) request).getOriginal();
    }
    return (req instanceof HttpUriRequest && ((HttpUriRequest)req).isAborted());
}
项目:java-logging    文件:OutboundRequestLoggingInterceptor.java   
@Override
public void process(HttpRequest request, HttpContext context) {
    RequestLine requestLine = request.getRequestLine();

    context.setAttribute("startedOn", clock.millis());
    context.setAttribute("method", requestLine.getMethod());
    context.setAttribute("url", context.getAttribute(HTTP_TARGET_HOST) + requestLine.getUri());

    LOG.info(appendEntries(requestMarkers(context)), "Outbound request start");
}
项目:cyberduck    文件:RequestEntityRestStorageService.java   
public RequestEntityRestStorageService(final S3Session session,
                                       final Jets3tProperties properties,
                                       final HttpClientBuilder configuration) {
    super(session.getHost().getCredentials().isAnonymousLogin() ? null :
                    new AWSCredentials(null, null) {
                        @Override
                        public String getAccessKey() {
                            return session.getHost().getCredentials().getUsername();
                        }

                        @Override
                        public String getSecretKey() {
                            return session.getHost().getCredentials().getPassword();
                        }
                    },
            new PreferencesUseragentProvider().get(), null, properties);
    this.session = session;
    configuration.disableContentCompression();
    configuration.setRetryHandler(new S3HttpRequestRetryHandler(this, preferences.getInteger("http.connections.retry")));
    configuration.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
            if(response.containsHeader("x-amz-bucket-region")) {
                final String host = ((HttpUriRequest) request).getURI().getHost();
                if(!StringUtils.equals(session.getHost().getHostname(), host)) {
                    regionEndpointCache.putRegionForBucketName(
                            StringUtils.split(StringUtils.removeEnd(((HttpUriRequest) request).getURI().getHost(), session.getHost().getHostname()), ".")[0],
                            response.getFirstHeader("x-amz-bucket-region").getValue());
                }
            }
            return super.getRedirect(request, response, context);
        }
    });
    this.setHttpClient(configuration.build());
}
项目:lams    文件:DecompressingHttpClient.java   
public <T> T execute(HttpHost target, HttpRequest request,
        ResponseHandler<? extends T> responseHandler, HttpContext context)
        throws IOException, ClientProtocolException {
    HttpResponse response = execute(target, request, context);
    try {
        return responseHandler.handleResponse(response);
    } finally {
        HttpEntity entity = response.getEntity();
        if (entity != null) EntityUtils.consume(entity);
    }
}
项目:Mobike    文件:PreemtiveAuthorizationHttpRequestInterceptor.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
            ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        Credentials creds = credsProvider.getCredentials(authScope);
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
项目:lams    文件:RequestUserAgent.java   
public void process(final HttpRequest request, final HttpContext context)
    throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (!request.containsHeader(HTTP.USER_AGENT)) {
        String useragent = HttpProtocolParams.getUserAgent(request.getParams());
        if (useragent != null) {
            request.addHeader(HTTP.USER_AGENT, useragent);
        }
    }
}
项目:sbc-qsystem    文件:StatisticUsers.java   
@Override
public Response getDialog(String driverClassName, String url, String username, String password,
    HttpRequest request, String errorMessage) {
    return getDialog("/ru/apertum/qsystem/reports/web/get_period_for_statistic_users.html",
        request,
        errorMessage);
}
项目:smart_plan    文件:DatabaseQueryRequestHanlder.java   
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    //处于线程之中.
    Log.d("plan", "DatabaseQueryRequestHanlder");
    response.setEntity(new StringEntity(getDataResponse(), "utf-8"));
    response.setStatusCode(200);
}
项目:HiTSDB-Client    文件:HiTSDBHttpAsyncCallbackExecutor.java   
private void tryCloseConnection(HttpRequest request) {
    Header[] headers = request.getHeaders("Connection");
    if (headers != null && headers.length > 0) {
        for (Header h : headers) {
            request.removeHeader(h);
        }
    }

    request.addHeader("Connection", "close");
}
项目:sbc-qsystem    文件:DistributionWaitDay.java   
@Override
public Response getDialog(String driverClassName, String url, String username, String password,
    HttpRequest request, String errorMessage) {
    final Response result = getDialog(
        "/ru/apertum/qsystem/reports/web/get_date_distribution.html",
        request, errorMessage);
    try {
        result.setData(new String(result.getData(), "UTF-8").replaceFirst("#DATA_FOR_TITLE#",
            RepResBundle.getInstance().getStringSafe("distribution_wait_day"))
            .getBytes("UTF-8"));
    } catch (UnsupportedEncodingException ex) {
    }
    return result;
}
项目:boohee_v5.6    文件:b.java   
private <T> T a(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws Exception {
    try {
        return this.c.execute(httpHost, httpRequest, responseHandler, httpContext);
    } catch (Throwable e) {
        throw new Exception(e);
    }
}
项目:logregator    文件:HttpCollectorHandlerTest.java   
private HttpRequest buildLogHttpRequest(String content) throws UnsupportedEncodingException {
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/log");
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(content.getBytes("UTF-8")));
    request.setEntity(entity);
    return request;
}
项目:integration-test-helper    文件:AomHttpClient.java   
private void setAuthorizationHeader( HttpRequest requestMethod )
{
    /* First try basic auth */
    String authHeader = getAuthenticationHeaderBasic( );
    /* If null, try Oauth */
    if ( authHeader == null )
    {
        authHeader = getAuthenticationHeaderBearer( );
    }
    /* Set header if not null, otherwise don't set header */
    if ( authHeader != null )
    {
        requestMethod.addHeader( "Authorization", authHeader );
    }
}
项目:ats-framework    文件:GGSSchemeBase.java   
/**
 * @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
 */
@Deprecated
public Header authenticate(
                            final Credentials credentials,
                            final HttpRequest request ) throws AuthenticationException {

    return authenticate(credentials, request, null);
}
项目:sbc-qsystem    文件:QReportsList.java   
private boolean checkLogin(HttpRequest request) {
    boolean res = false;
    // в запросе должен быть пароль и пользователь, если нету, то отказ на вход
    String entityContent = NetUtil.getEntityContent(request);
    QLog.l().logger().trace("Принятые параметры \"" + entityContent + "\".");
    // ресурс для выдачи в браузер. это либо список отчетов при корректном логининге или отказ на вход
    // разбирем параметры
    final HashMap<String, String> cookie = NetUtil.getCookie(entityContent, "&");
    if (cookie.containsKey("username") && cookie.containsKey("password")) {
        if (isTrueUser(cookie.get("username"), cookie.get("password"))) {
            res = true;
        }
    }
    return res;
}
项目:outcomes    文件:TestHttpCore.java   
@Test
public void test() throws ExecutionException, InterruptedException {


    HttpHost target = new HttpHost("localhost");
    BasicConnPool connpool = new BasicConnPool();
    connpool.setMaxTotal(200);
    connpool.setDefaultMaxPerRoute(10);
    connpool.setMaxPerRoute(target, 20);
    Future<BasicPoolEntry> future = connpool.lease(target, null);
    BasicPoolEntry poolEntry = future.get();
    HttpClientConnection conn = poolEntry.getConnection();

    HttpProcessor httpproc = HttpProcessorBuilder.create()
            .add(new ResponseDate())
            .add(new ResponseServer("MyServer-HTTP/1.1"))
            .add(new ResponseContent())
            .add(new ResponseConnControl())
            .build();

    HttpRequestHandler myRequestHandler = new HttpRequestHandler() {

        public void handle(
                HttpRequest request,
                HttpResponse response,
                HttpContext context) throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(
                    new StringEntity("some important message",
                            ContentType.TEXT_PLAIN));
        }

    };

    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    handlerMapper.register("/service/*", myRequestHandler);
    HttpService httpService = new HttpService(httpproc, handlerMapper);
}
项目:cyberduck    文件:SDSErrorResponseInterceptor.java   
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if(StringUtils.isNotBlank(token)) {
        request.removeHeaders(SDSSession.SDS_AUTH_TOKEN_HEADER);
        request.addHeader(SDSSession.SDS_AUTH_TOKEN_HEADER, token);
    }
}
项目:lams    文件:LtiOauthSigner.java   
private String getRequestBody(HttpRequest req) throws IOException {
    if(req instanceof HttpEntityEnclosingRequest){
        HttpEntity body = ((HttpEntityEnclosingRequest) req).getEntity();
        if(body == null) {
            return "";
        } else {
            return IOUtils.toString(body.getContent());
        }
    } else {
        // requests with no entity have an empty string as the body
        return "";
    }
}
项目:sbc-qsystem    文件:RatioServices.java   
/**
 * Метод получения коннекта к базе если отчет строится через коннект. Если отчет строится не
 * через коннект, а формироватором, то выдать null.
 *
 * @return коннект соединения к базе или null.
 */
@Override
public Connection getConnection(String driverClassName, String url, String username,
    String password, HttpRequest request) {
    final Connection connection;
    try {
        Class.forName(driverClassName);
        connection = DriverManager.getConnection(url, username, password);
    } catch (SQLException | ClassNotFoundException ex) {
        throw new ReportException(RatioServices.class.getName() + " " + ex);
    }
    return connection;
}
项目:JInsight    文件:RequestExecutorBasedClientInstrumentationTest.java   
public HttpResponse doGET(URI url) throws IOException, HttpException {
  String uri = url.getRawPath() + (url.getRawQuery() != null ? "?" + url.getRawQuery() : "");
  HttpRequest request = new BasicHttpRequest("GET", uri);
  String hostHeader = (url.getPort() == 0 || url.getPort() == 80)
      ? url.getHost() : (url.getHost() + ":" + url.getPort());
  request.addHeader("Host", hostHeader);
  return execute(request);
}
项目:Photato    文件:PhotatoHandler.java   
@Override
public final void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    if (!this.allowedVerbs.contains(request.getRequestLine().getMethod().toUpperCase())) {
        response.setStatusCode(http403.responseCode);
        response.setEntity(http403.entity);
    } else {
        Tuple<String, Map<String, String>> pathAndQueryTuple = PathHelper.splitPathAndQuery(request.getRequestLine().getUri().substring(this.prefix.length()));
        String path = pathAndQueryTuple.o1;

        Map<String, String> query = pathAndQueryTuple.o2;

        if (this.isAuthorized(path, query)) {
            try {
                Response res = getResponse(path, query);
                response.setStatusCode(res.responseCode);
                response.setHeaders(res.headers);
                response.setEntity(res.entity);
            } catch (Exception ex) {
                response.setStatusCode(http500.responseCode);
                response.setEntity(http500.entity);
                ex.printStackTrace();
            }
        } else {
            response.setStatusCode(http403.responseCode);
            response.setEntity(http403.entity);
        }
    }
}
项目:lams    文件:HttpRequestExecutor.java   
/**
 * Decide whether a response comes with an entity.
 * The implementation in this class is based on RFC 2616.
 * <br/>
 * Derived executors can override this method to handle
 * methods and response codes not specified in RFC 2616.
 *
 * @param request   the request, to obtain the executed method
 * @param response  the response, to obtain the status code
 */
protected boolean canResponseHaveBody(final HttpRequest request,
                                      final HttpResponse response) {

    if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
        return false;
    }
    int status = response.getStatusLine().getStatusCode();
    return status >= HttpStatus.SC_OK
        && status != HttpStatus.SC_NO_CONTENT
        && status != HttpStatus.SC_NOT_MODIFIED
        && status != HttpStatus.SC_RESET_CONTENT;
}
项目:lams    文件:AbstractHttpClient.java   
public <T> T execute(
        final HttpHost target,
        final HttpRequest request,
        final ResponseHandler<? extends T> responseHandler)
            throws IOException, ClientProtocolException {
    return execute(target, request, responseHandler, null);
}
项目:datarouter    文件:LoggingRedirectStrategy.java   
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
throws ProtocolException{
    HttpUriRequest redirect = super.getRedirect(request, response, context);
    logger.warn("Got a {}, will redirect {} to {}", response.getStatusLine(), request.getRequestLine(), redirect
            .getRequestLine());
    return redirect;
}
项目:lams    文件:BasicHttpProcessor.java   
public void process(
        final HttpRequest request,
        final HttpContext context)
        throws IOException, HttpException {
    for (int i = 0; i < this.requestInterceptors.size(); i++) {
        HttpRequestInterceptor interceptor =
            this.requestInterceptors.get(i);
        interceptor.process(request, context);
    }
}
项目:orange-mathoms-logging    文件:HttpRequestHandlerWithMdcPropagation.java   
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    for (Entry<String, String> e : mdcName2HeaderName.entrySet()) {
        String mdcValue = MDC.get(e.getKey());
        if (mdcValue != null) {
            request.addHeader(new BasicHeader(e.getValue(), mdcValue));
        }
    }
}
项目:sbc-qsystem    文件:AuthorizedClientsPeriodUsers.java   
@Override
public String validate(String driverClassName, String url, String username, String password,
    HttpRequest request, HashMap<String, String> params) {
    // проверка на корректность введенных параметров
    QLog.l().logger().trace("Принятые параметры \"" + params.toString() + "\".");
    if (params.size() == 4) {
        // sd/ed/user_id/user
        Date sd, fd;
        String sdate, fdate, user;
        long user_id;
        try {
            //date = Uses.FORMAT_DD_MM_YYYY.parse(ss0[1]);
            sd = Uses.FORMAT_DD_MM_YYYY.parse(params.get("sd"));
            fd = Uses.FORMAT_DD_MM_YYYY.parse(params.get("ed"));
            sdate = (new java.text.SimpleDateFormat("yyyy-MM-dd")).format(sd);
            fdate = (new java.text.SimpleDateFormat("yyyy-MM-dd")).format(fd);
            user_id = Long.parseLong(params.get("user_id"));
            user = params.get("user");
        } catch (ParseException | NumberFormatException ex) {
            return "<br>Ошибка ввода параметров! Не все параметры введены корректно (дд.мм.гггг).";
        }
        paramMap.put("sdate", sdate);
        paramMap.put("fdate", fdate);
        paramMap.put("sd", sd);
        paramMap.put("fd", fd);
        paramMap.put("user_id", user_id);
        paramMap.put("user", user);
    } else {
        return "<br>Ошибка ввода параметров!";
    }
    return null;
}
项目:boohee_v5.6    文件:PreemptiveAuthorizationHttpRequestInterceptor.java   
public void process(HttpRequest request, HttpContext context) throws HttpException,
        IOException {
    AuthState authState = (AuthState) context.getAttribute("http.auth.target-scope");
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute("http.auth" +
            ".credentials-provider");
    HttpHost targetHost = (HttpHost) context.getAttribute("http.target_host");
    if (authState.getAuthScheme() == null) {
        Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName
                (), targetHost.getPort()));
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}