This post will explain us, how can we call REST API using Webclient.
How to set Proxy username and password to call the external site.
Step 1: Add folllowing dependency in your pom.xml
org.springframework.boot
spring-boot-starter-webflux
Step 2:
import lombok.extern.slf4j.XSlf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.transport.ProxyProvider;
import java.net.URI;
import java.util.Base64;
import java.util.function.Consumer;
import java.util.function.Function;
public static void main(String[] args) {
try {
//Generate HttP client to set proxy details
HttpClient httpClient = HttpClient.create()
.proxy(proxy-> proxy.type(ProxyProvider.Proxy.HTTP)
.host("javaguruonline.com").port(1328)
.username("siva")
.password(new Function() {
@Override
public String apply(String s) {
return "test@12!";
}
}));
ClientHttpConnector clientHttpConnector =
new ReactorClientHttpConnector(httpClient);
WebClient webClient = WebClient.builder().build();
String plainCredentials = "username" + ":" + "password";
String base64Credentials = new String(Base64.getEncoder()
.encode(plainCredentials.getBytes()));
String authorizationHeader = "Basic " + base64Credentials;
//input json
String json = "{\n" +
" \"user\": \"siva\"\n" +
"}";
//set http headers
Consumer httpHeaders = new Consumer() {
@Override
public void accept(HttpHeaders httpHeaders) {
httpHeaders.add("Authorization", authorizationHeader);
httpHeaders.add("Content-Type", "application/json");
httpHeaders.add("Proxy-Authorization", authorizationHeader);
}};
//post call to external URL and get ResponseEntity as response like body
//and http status code etc..
ResponseEntity result = webClient.mutate()
.clientConnector(clientHttpConnector)
.build()
.post()
.uri(new URI("https://localhost:8080/test/details"))
.bodyValue(json)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntity(String.class)
.block();
System.out.println(result);
}
catch(Exception ex){
}
Hope this post will help some one, while working on the REST API calls
No comments:
Post a Comment