Invoking RESTful WebServices Behind The Proxy

Types of proxy networks
Invoke REST api calls behind the proxy using spring RestTemplate and using simple HTTPUrlConnection instance.

You will learn how to make Third party RESTful apis calls or invoking your micro services which are deployed in different domain. What are additional properties that you need to set to make this rest calls beyond the proxy.

This is useful when your organization network running beyond the proxy but you need to make the calls the external services from your application.

Types of proxy networks

  • SOCKS: This is general purpose proxy server that establishes a TCP connection to another server on behalf of the client, then routes all the traffic back and forth between the client and the server. It works any kind of protocol (SSH,WebSocket etc) and any port. SOCKS5 adds additional support for security and UDP.

  • HTTP: Used to handle high level protocols such as HTTP or FTP. HTTP proxy used to handle HTTP traffic. Since our RESTful are also only works with HTTP protocol. we will use HTTP proxy configuration to make REST calls to the server.

HTTPURLConnection API that users proxy

I have created simple REST client with works inside the proxy network. there might be slight changes to the headers as per your services. below is complete code for this.

SimpleRESTClient.java
package com.trvajjala;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.util.logging.Logger;

public class SimpleRESTClient {

    static Logger LOG = Logger.getLogger(SimpleRESTClient.class.getName());
    private static final String API_ENDPOINT = "http://api.trvajjala.com";

    public static void main(String[] args) throws Exception {

        /** First step you need authenticate your Proxy with below code snippet */
        Authenticator.setDefault(new ProxyAuthentication(new PasswordAuthentication("ProxyUsername", "ProxyPassword".toCharArray())));

        /** Prepare proxy instance with host and port details */
        final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.1.1", 3124));

        doPost("/get-details", "{YOUR JSON PAYLOAD}", "pass authentication token if any change header name as per your services", proxy);

    }

    public static String doPost(String uri, String payload, String token, Proxy proxy) throws Exception {

        try {

            LOG.info("Making POST call to the Wyzbee Api with the uri :" + uri);

            LOG.info("\n" + payload + "\n");

            if ((uri == null) || (payload == null)) {
                LOG.info("Invalid endpoint or payload supplied.");
                throw new Exception("Invalid endpoint or payload supplied.");
            }

            final URL url = new URL(API_ENDPOINT + uri);
            final HttpURLConnection connection = (HttpURLConnection) ((proxy == null) ? url.openConnection() : url.openConnection(proxy));
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestMethod("POST");
            if (token != null) {
                connection.setRequestProperty("Authorization", token);
            }

            final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(payload);
            writer.flush();
            writer.close();

            final StringBuilder responsePayload = new StringBuilder();
            final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;

            while ((line = reader.readLine()) != null) {
                responsePayload.append(line);
            }
            reader.close();

            LOG.info("Server Response code :: " + connection.getResponseCode());
            LOG.info("Server Response :: " + responsePayload);

            return responsePayload.toString();
        } catch (final IOException e) {
            LOG.severe("IOException :" + e);
            throw new Exception("Error while communicating with the services. Reason: " + e.getMessage(), e);
        }

    }

    public static String doGet(String uri, Proxy proxy) throws Exception {

        try {
            LOG.info("Making GET call to the wyzbee Api with the uri " + uri);

            final URL url = new URL(API_ENDPOINT + uri);
            final HttpURLConnection connection = (HttpURLConnection) ((proxy == null) ? url.openConnection() : url.openConnection(proxy));
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestMethod("GET");

            final StringBuilder responsePayload = new StringBuilder();
            final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            reader.close();
            while ((line = reader.readLine()) != null) {
                responsePayload.append(line);
            }
            reader.close();

            return responsePayload.toString();

        } catch (final IOException e) {
            LOG.severe("IO Exception :" + e.getMessage());
            throw new Exception(e);
        }
    }

}

class ProxyAuthentication extends Authenticator {

    private final PasswordAuthentication passwordAuthentication;

    public ProxyAuthentication(PasswordAuthentication passwordAuthentication) {
        this.passwordAuthentication = passwordAuthentication;
    }

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        return this.passwordAuthentication;
    }
}

Adding Proxy configuration to RestTemplate

filename.java
       final Authenticator authenticator = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return (new PasswordAuthentication("proxyUsername", "proxyPassword".toCharArray()));
            }
        };

        Authenticator.setDefault(authenticator);

        final SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        final InetSocketAddress address = new InetSocketAddress("proxyHost", proxyPort);
        final Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
        factory.setProxy(proxy);

        final RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(factory);// (1)
  1. Pass Factory instance to RestTemplate

Comments

Popular posts from this blog

IBM Datapower GatewayScript

Spring boot Kafka Integration

Spring boot SOAP Web Service Performance