java rest interceptor example
Example 1: java http interceptor
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HttpContext;
public class InterceptorsExample {
public static void main(String args[]) throws Exception{
HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws
HttpException, IOException {
if(request.containsHeader("sample-header")) {
System.out.println("Contains header sample-header, removing it..");
request.removeHeaders("sample-header");
}
Header[] headers= request.getAllHeaders();
for (int i = 0; i<headers.length;i++) {
System.out.println(headers[i].getName());
}
}
};
CloseableHttpClient httpclient =
HttpClients.custom().addInterceptorFirst(requestInterceptor).build();
HttpGet httpget1 = new HttpGet("https://www.tutorialspoint.com/");
httpget1.setHeader(new BasicHeader("sample-header","My first header"));
httpget1.setHeader(new BasicHeader("demo-header","My second header"));
httpget1.setHeader(new BasicHeader("test-header","My third header"));
HttpResponse httpresponse = httpclient.execute(httpget1);
System.out.println(httpresponse.getStatusLine());
}
}
Example 2: java http interceptor
@Override
public void process(HttpRequest request, HttpContext context) throws
HttpException, IOException {
};