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); } }
@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); }
@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); }
/** * 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 (); }
@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); }
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 }
@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; }); }
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)); } }
@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); } }
/** * 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()); }
/** * 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; }
/** * 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; }
/** * @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()); }
@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"); }
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()); }
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); } }
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); } } }
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); } } }
@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); }
@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); }
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"); }
@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; }
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); } }
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; }
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 ); } }
/** * @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); }
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; }
@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); }
@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); } }
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 ""; } }
/** * Метод получения коннекта к базе если отчет строится через коннект. Если отчет строится не * через коннект, а формироватором, то выдать 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; }
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); }
@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); } } }
/** * 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; }
public <T> T execute( final HttpHost target, final HttpRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { return execute(target, request, responseHandler, null); }
@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; }
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); } }
@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)); } } }
@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; }
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); } } }