logo
down
shadow

Add a header to an outgoing request by a filter in WebFlux


Add a header to an outgoing request by a filter in WebFlux

By : crackers500
Date : October 17 2020, 06:10 AM
wish helps you There are multiple ways of specifying custom headers.
If the headers are static, you can specify them during WebClient instance creation using defaultHeader or defaultHeaders methods:
code :
WebClient.builder().defaultHeader("headerName", "headerValue")
WebClient.builder().defaultHeaders(headers -> headers.add("h1", "hv1").add("h2", "hv2"))
WebClient
    .builder()
    .filter(ExchangeFilterFunction.ofRequestProcessor(
        request -> Mono.just(ClientRequest.from(request)
                                          .header("X-HEADER-NAME", "value")
                                          .build())
    )
    .build();
webClient.get()
    .header("headerName", getHeaderValue(params))
    .retrieve();


Share : facebook icon twitter icon
Add Header To all outgoing CXF request

Add Header To all outgoing CXF request


By : F. Bologni
Date : March 29 2020, 07:55 AM
will be helpful for those in need Is it possible to add a Header to all outgoing cxf connections, from the client side. , this is how i did,
Spring.xml
code :
<import resource="classpath:META-INF/cxf/cxf.xml" />

<bean id="cxf" class="org.apache.cxf.bus.spring.SpringBus">
    <property name="outInterceptors">
        <list>
            <ref bean="headerInterceptor"/>
        </list>
    </property>
    <property name="inInterceptors">
        <list>
            <ref bean="headerInterceptor"/>
        </list>
    </property>
</bean>

<bean id="headerInterceptor" class="logging.Interceptor"/>
 public class UUIDHeaderInterceptor extends AbstractPhaseInterceptor {


private static final Logger logger = LoggerFactory.getLogger(UUIDHeaderInterceptor.class);



public UUIDHeaderInterceptor() {
    super(Phase.RECEIVE);

}

@Override
public void handleMessage(Message message) throws Fault {

        Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
        headers.put(REQUEST_ID_ATTRIBUTE_NAME, Arrays.asList(new String[]{"TEST"}));

   }
 }

@Override
public void handleFault(Message message) {
    handleMessage(message);
  }
How can I assert a header on an outgoing Mule Request with an Munit Spy

How can I assert a header on an outgoing Mule Request with an Munit Spy


By : user3481835
Date : March 29 2020, 07:55 AM
it should still fix some issue Hi there not sure there is a way to do what you want.
You see if you as it was suggested, and set the headers as outbound properties before hand, then you can run assertions in the spy before section and validate that those outbound variables are there.
code :
<http:request doc:name="unnamedImportApi"
        config-ref="HTTP_Request_Configuration"
        path="${outgoing.api.base_path}/import" method="POST">
        <http:request-builder>
            <http:header headerName="Authorization" value="Token token=#[flowVars['api_key']]"/>
        </http:request-builder>
    </http:request>
spyData.put("authHeader", event.getMessage().getInvocationProperty("api_key"));
<http:header headerName
Add request header to ALL outgoing requests within a WKWebView

Add request header to ALL outgoing requests within a WKWebView


By : Purshotam Bhasima
Date : March 29 2020, 07:55 AM
wish helps you It is impossible with current API - there is no point where you can handle all requests that made by WKWebView. You can use UIWebView + custom url protocol (WKWebView doesn't support it) and add your header to all requests for certain server as an alternative.
Webflux, How to intercept a request and add a new header

Webflux, How to intercept a request and add a new header


By : user3294915
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You can mutate the ServerWebExchange and its ServerHttpRequest with their mutate() methods which returns a 'Builder' for each of them.
Example Java:
code :
@Component
public class AuthorizationFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest mutatedRequest = exchange.getRequest().mutate().header(HttpHeaders.AUTHORIZATION, "Bearer " + authHeader).build();
        ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
        return chain.filter(mutatedExchange);
    }
}
@Component
class AuthorizationFilter : WebFilter {
    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
        val mutatedRequest = exchange.request.mutate().header(HttpHeaders.AUTHORIZATION, "Bearer $authHeader").build()
        val mutatedExchange = exchange.mutate().request(mutatedRequest).build()
        return chain.filter(mutatedExchange)
    }
}
Is there a way to automatically propagate an incoming HTTP header in a JAX-RS request to an outgoing JAX-RS request?

Is there a way to automatically propagate an incoming HTTP header in a JAX-RS request to an outgoing JAX-RS request?


By : Hugo Magalhães
Date : March 29 2020, 07:55 AM
wish help you to fix your issue What I would do is make a WebTarget injectable that is preconfigured with a ClientRequestFilter to add the headers. It's better to configure the WebTarget this way, as opposed to the Client, since the Client is an expensive object to create.
We can make the WebTarget injectable using a custom annotation and an InjectionResolver. In the InjectionResolver, we can get the ContainerRequest and get the headers from that, which we will pass to the ClientRequestFilter.
code :
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface WithHeadersTarget {
    String baseUri();
    String[] headerNames() default {};
}
private static class WithHeadersTargetInjectionResolver
        implements InjectionResolver<WithHeadersTarget> {

    private final Provider<ContainerRequest> requestProvider;
    private final Client client;

    @Inject
    public WithHeadersTargetInjectionResolver(Provider<ContainerRequest> requestProvider) {
        this.requestProvider = requestProvider;
        this.client = ClientBuilder.newClient();
    }

    @Override
    public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
        if (injectee.getRequiredType() == WebTarget.class
                && injectee.getParent().isAnnotationPresent(WithHeadersTarget.class)) {
            WithHeadersTarget anno = injectee.getParent().getAnnotation(WithHeadersTarget.class);
            String uri = anno.baseUri();
            String[] headersNames = anno.headerNames();
            MultivaluedMap<String, String> requestHeaders = requestProvider.get().getRequestHeaders();

            return client.target(uri)
                    .register(new HeadersFilter(requestHeaders, headersNames));
        }
        return null;
    }

    @Override
    public boolean isConstructorParameterIndicator() {
        return false;
    }

    @Override
    public boolean isMethodParameterIndicator() {
        return false;
    }

    private class HeadersFilter implements ClientRequestFilter {

        private final MultivaluedMap<String, String> headers;
        private final String[] headerNames;

        private HeadersFilter(MultivaluedMap<String, String> headers, String[] headerNames) {
            this.headers = headers;
            this.headerNames = headerNames;
        }

        @Override
        public void filter(ClientRequestContext requestContext) throws IOException {
            // if headers names is empty, add all headers
            if (this.headerNames.length == 0) {
                for (Map.Entry<String, List<String>> entry: this.headers.entrySet()) {
                    requestContext.getHeaders().put(entry.getKey(), new ArrayList<>(entry.getValue()));
                }
            // else just add the headers from the annotation
            } else {
                for (String header: this.headerNames) {
                    requestContext.getHeaders().put(header, new ArrayList<>(this.headers.get(header)));
                }
            }
        }
    }
}
new ResourceConfig()
   .register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(WithHeadersTargetInjectionResolver.class)
                  .to(new TypeLiteral<InjectionResolver<WithHeadersTarget>>() {
                   }).in(Singleton.class);
            }
        })
@Path("test")
public static class TestResource {

    @WithHeadersTarget(
            baseUri = BASE_URI
            headerNames = {TEST_HEADER_NAME})
    private WebTarget target;

    @GET
    public String get() {
        return target.path("client").request().get(String.class);
    }
}
import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import static org.assertj.core.api.Assertions.assertThat;

public class ForwardHeadersTest extends JerseyTest {

    private static final String BASE_URI = "http://localhost:8000";
    private static final String TEST_HEADER_NAME = "X-Test-Header";

    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface WithHeadersTarget {
        String baseUri();
        String[] headerNames() default {};
    }

    @Path("test")
    public static class TestResource {

        @WithHeadersTarget(
                baseUri = BASE_URI
                )
        private WebTarget target;

        @GET
        public String get() {
            return target.path("client").request().get(String.class);
        }
    }

    @Path("client")
    public static class ClientResource {

        @GET
        public String getReversedHeader(@HeaderParam(TEST_HEADER_NAME) String header) {
            System.out.println(header);
            return new StringBuilder(header).reverse().toString();
        }
    }

    private static class WithHeadersTargetInjectionResolver
            implements InjectionResolver<WithHeadersTarget> {

        private final Provider<ContainerRequest> requestProvider;
        private final Client client;

        @Inject
        public WithHeadersTargetInjectionResolver(Provider<ContainerRequest> requestProvider) {
            this.requestProvider = requestProvider;
            this.client = ClientBuilder.newClient();
        }

        @Override
        public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
            if (injectee.getRequiredType() == WebTarget.class
                    && injectee.getParent().isAnnotationPresent(WithHeadersTarget.class)) {
                WithHeadersTarget anno = injectee.getParent().getAnnotation(WithHeadersTarget.class);
                String uri = anno.baseUri();
                String[] headersNames = anno.headerNames();
                MultivaluedMap<String, String> requestHeaders = requestProvider.get().getRequestHeaders();

                return client.target(uri)
                        .register(new HeadersFilter(requestHeaders, headersNames));
            }
            return null;
        }

        @Override
        public boolean isConstructorParameterIndicator() {
            return false;
        }

        @Override
        public boolean isMethodParameterIndicator() {
            return false;
        }

        private class HeadersFilter implements ClientRequestFilter {

            private final MultivaluedMap<String, String> headers;
            private final String[] headerNames;

            private HeadersFilter(MultivaluedMap<String, String> headers, String[] headerNames) {
                this.headers = headers;
                this.headerNames = headerNames;
            }

            @Override
            public void filter(ClientRequestContext requestContext) throws IOException {
                // if headers names is empty, add all headers
                if (this.headerNames.length == 0) {
                    for (Map.Entry<String, List<String>> entry: this.headers.entrySet()) {
                        requestContext.getHeaders().put(entry.getKey(), new ArrayList<>(entry.getValue()));
                    }
                // else just add the headers from the annotation
                } else {
                    for (String header: this.headerNames) {
                        requestContext.getHeaders().put(header, new ArrayList<>(this.headers.get(header)));
                    }
                }
            }
        }
    }

    @Override
    public ResourceConfig configure() {
        return new ResourceConfig()
                .register(TestResource.class)
                .register(ClientResource.class)
                .register(new AbstractBinder() {
                    @Override
                    protected void configure() {
                        bind(WithHeadersTargetInjectionResolver.class)
                                .to(new TypeLiteral<InjectionResolver<WithHeadersTarget>>() {
                                }).in(Singleton.class);
                    }
                })
                .register(new LoggingFilter(Logger.getAnonymousLogger(), true))
                .register(new ExceptionMapper<Throwable>() {
                    @Override
                    public Response toResponse(Throwable t) {
                        t.printStackTrace();
                        return Response.serverError().entity(t.getMessage()).build();
                    }
                });
    }

    @Override
    public URI getBaseUri() {
        return URI.create(BASE_URI);
    }

    @Test
    public void testIt() {
        final String response = target("test")
                .request()
                .header(TEST_HEADER_NAME, "HelloWorld")
                .get(String.class);

        assertThat(response).isEqualTo("dlroWolleH");
    }
}
Related Posts Related Posts :
  • Static value in for loop
  • Difference between Class c; and Class c=new Class();
  • My question is about Regular Expression in java
  • Why can't I write ch=ch+1; instead of ch++; though they have same meaning
  • Why is this loop changed?
  • Java (Read and write to file)
  • What's ideal debugging setup? window placement etc
  • Java app behind proxy to use http_proxy variable in linux
  • Straight Java/Groovy versus ETL tool (Talend/etc) - what libraries would you use?
  • Performance testing Flex applications
  • How to insert into two different tables in one statement with Java and MySQL?
  • Object Serialization for Undo/Redo Functionality Java
  • How to retrieve the last image from an SDcard in Android?
  • What's the fastest way to draw a Hello World in Java
  • Java error on bilinear interpolation of 16 bit data
  • Java equivalent for database schema changes like South for Django?
  • Java Robot key activity seems to stop working while certain software is running
  • Will using multiple version of a jar in an application cause problems?
  • JSF RuntimeException: Cannot find FacesContext
  • How do i get a particular day from Jan to Dec
  • Hibernate configuration for Mysql 8.0
  • What JVM can run on CPU and GPU?
  • How to cast an image received from a webservice in Binary64 format to actual image?
  • Is there anyway to get the generated keys when using Spring JDBC batchUpdate?
  • How good is Oracle Universal Connection Pool (UCP)
  • How to populate Java (web) application with initial data using Spring/JPA/Hibernate
  • How do I make my frames change in java?
  • Java Swing - Background of a JPanel
  • Printing pdf from extjs - best solution
  • Clean a RandomAccessFile
  • JFileChooser and browsing networked machines
  • How to write Java string literals that contain double-quotes (")?
  • What do I use Artifacts in IntelliJ IDEA for?
  • Bug with Spring Security 3.0.2 x Spring 3.0.1 - Proxies not being created
  • DBunit generates java.lang.ClassCastException: java.lang.String cannot be cast to oracle.sql.CLOB when trying to load a
  • Hibernate configuration - session factory scanning?
  • Enter Key Press behave like Submit in JSF
  • Using protocol buffers for binary logging
  • EasyMock Class Extension mock isn't mocking methods
  • How do I convert a byte array to Base64 in Java?
  • How to modify camel Exchange and send it
  • How do I avoid constructors?
  • Passing string in where clause using PreparedStatement
  • Tomcat 7 - Ignoring db conections pool parameters (DBCP)
  • How does reduce() method work with parallel streams in Java 8?
  • How can I use a generic class with wildcard declaration?
  • Unable to add ArrayList with multiple arguments
  • Move application into second window monitor in javafx
  • does intern() method have implication on performance?
  • How to run NPM Command in Java code using ProcessBuilder
  • Sending HTTP/2 request via Socket in Java
  • eclipse IDE wrong warning that unused field
  • Decode Java enum from single char
  • How to hide embedded dependencies when using an OSGI bundle with maven?
  • How to correctly implement a generic interface in Java
  • send alert to html page from servlet
  • <EOF>Exception while creating Derby table
  • What does stack.pop() return?
  • Problem with Java Language Levels in IntelliJ IDEA
  • How do i get the status code for a response i subscribe to using the JDK's HttpClient?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk