Java to SF
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.tcp.ProxyProvider;
/*
dependencies:
compile group: 'org.springframework.boot', name: 'spring-boot-starter-webflux', version: '2.1.0.RELEASE'
compile group: 'org.projectreactor', name: 'reactor-spring', version: '1.0.1.RELEASE'
compile group: 'com.google.guava', name: 'guava', version: '27.0-jre'
compile group: 'org.projectlombok', name: 'lombok', version: '1.18.4'
lombok.config in root of the project:
lombok.anyConstructor.addConstructorProperties=true
config.stopBubbling = true
*/
public class RestClient {
public String send() throws Exception {
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
HttpClient httpClient = HttpClient.create()
.followRedirect(true)
.tcpConfiguration(tcpClient ->
tcpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP).host("localhost").port(8080))
)
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
final WebClient authClient = WebClient
.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
final String token = "WIvZl6Ka7pB6XYo0eor2Jvw8b";
final AuthResponse authResponse = authClient
.post()
.uri("https://login.salesforce.com/services/oauth2/token")
.body(BodyInserters
.fromFormData("grant_type", "password")
.with("client_id", "AAAA")
.with("client_secret", "BBBB")
.with("username", "YYYYY")
.with("password", "XXXXX" + token)
)
.retrieve()
.bodyToMono(AuthResponse.class)
.blockOptional()
.orElseThrow(() -> new IllegalStateException("No response received"));
final WebClient client = WebClient
.builder()
.baseUrl(authResponse.getInstanceUrl())
.defaultHeader("Authorization", "Bearer " + authResponse.getAccessToken())
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
final String data = client
.get()
.uri("services/data/v44.0/")
.retrieve()
.bodyToMono(String.class)
.retry(3)
.block();
return data;
}
@Value
@Builder
public class AuthResponse {
@JsonAlias("access_token")
private final String accessToken;
@JsonAlias("instance_url")
private final String instanceUrl;
private final String id;
@JsonAlias("token_type")
private final String tokenType;
@JsonAlias("issued_at")
private final String issuedAt;
private final String signature;
}
}