[JAX-RS] 4 ways to implement a client for web services

1. URLConnection client [code language=”java”] package com.vvirlan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class URLConnectionClient { public static void main(String[] args) throws IOException { URL restURL = new URL("http://localhost:8080/simple-service-webapp/resources/myresource/usernamepwdcontext"); URLConnection connection = (URLConnection) restURL.openConnection(); connection.setDoOutput(true); connection.connect(); InputStreamReader ins = new InputStreamReader(connection.getInputStream()); BufferedReader in = new BufferedReader(ins); String inputLine; while ((inputLine…

[JAX-RS] 2 ways to get the Basic auth username and password

There are 2 ways at least to get the Basic auth username and password in a JAX-RS web method 1. Using the @HeaderParam(“Authorization”) annotation [code language=”java”] @GET @Path("/usernamepwd") public String getUsernamePassword(@HeaderParam("Authorization") String header) { if (header==null) { return "header is null"; } String authorization = header.substring("Basic ".length()); byte[] decodedPass = Base64.getDecoder().decode(authorization); System.out.println("Decoded pass: " +…

[STARTER] JAX-RS: Jersey + Servlet 3.0 + Maven + Tomcat

Steps to configure a JAX-RS project that runs on Tomcat (here 8), Maven, Servlet 3.0 and having Jersey as a Reference Implementation. 1. Maven POM.XML dependencies:

  2. web.xml (src/main/webapp/WEB-INF)  

3. Application class (under: src/main/java/com/vvirlan/java/ws

4. Resource class (which is the actual web service endpoint):  

5. Build the…