52

Using Java tools,

wscompile for RPC
wsimport for Document
etc..

I can use WSDL to generate the stub and Classes required to hit the SOAP Web Service.

But I have no idea how I can do the same in REST. How can I get the Java classes required for hitting the REST Web Service. What is the way to hit the service anyway?

Can anyone show me the way?

Mawia
  • 4,220
  • 13
  • 40
  • 55
  • See http://stackoverflow.com/questions/3048091/generic-open-source-rest-client –  Oct 16 '12 at 13:49
  • 1
    This like will help you http://stackoverflow.com/questions/221442/rest-clients-for-java – zaffargachal Oct 16 '12 at 13:51
  • Guys... I don't want to hit the Web Service using URLs. I want to hit using my Java Classes. Is there a way? – Mawia Oct 18 '12 at 09:14
  • check this 2 line of code https://stackoverflow.com/questions/12916169/how-to-consume-rest-in-java/48030636#answer-48030636 – Vishrant Dec 30 '17 at 03:20

11 Answers11

43

Working example, try this:

package restclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetClientGet {
    public static void main(String[] args) {
        try {

            URL url = new URL("http://localhost:3002/RestWebserviceDemo/rest/json/product/dynamicData?size=5");//your url i.e fetch data from .
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : "
                        + conn.getResponseCode());
            }
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String output;
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
MAnoj Sarnaik
  • 1,592
  • 16
  • 16
  • 1
    @OwenIvory what do you mean with apache hell? – Cyclonecode May 07 '19 at 14:44
  • I was initially told to use apache .jar files to accomplish a simple Restful query. So I downloaded some .jar files, but they were for the wrong version of java (not the one I was using). Then I found some that were the right version of java, but they were a mismatch of apache version, and thus the classes didn't contain the objects the example I was given had. Anyway, this example is straight java.net.... i.e. works with just the jdk installed. No messing with apache versions or acquiring jar files or compile problems, just JDK and go. – Owen Ivory May 08 '19 at 15:58
  • Hi, if my method is a Post and need to send a Json object ¿Is this possible in this method? Regards. – Ramiro Arizpe Giacomelli Dec 19 '19 at 18:58
  • I'm confused. Which method actually sends the request to the network? Is it `.openConnection()`? If so, why are you setting the request method and headers afterwards? Forgive me, but I'm still a beginner with java. – Peter Schorn Sep 18 '20 at 18:39
19

As others have said, you can do it using the lower level HTTP API, or you can use the higher level JAXRS APIs to consume a service as JSON. For example:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://host:8080/context/rest/method");
JsonArray response = target.request(MediaType.APPLICATION_JSON).get(JsonArray.class);
Holly Cummins
  • 10,767
  • 3
  • 23
  • 25
  • 3
    As suggested by Holly, JAX RS Client API (introduced in version 2.0) is much better way to consume REST APIs than low level URL + manual unmarshmaling. I'd suggest to get data as properly mapped Java beans instead of "raw json". A tutorial I wrote about this previously: https://vaadin.com/blog/-/blogs/consuming-rest-services-from-java-applications – mstahv Mar 10 '16 at 09:05
  • Can i do a POST request with this ? How i set the request's body? – Cesar Leonardo Ochoa Contreras Jan 24 '19 at 17:15
9

Its just a 2 line of code.

import org.springframework.web.client.RestTemplate;

RestTemplate restTemplate = new RestTemplate();
YourBean obj = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", YourBean.class);

Ref. Spring.io consuming-rest

Vishrant
  • 15,456
  • 11
  • 71
  • 120
4

The code below will help to consume rest api via Java. URL - end point rest If you dont need any authentication you dont need to write the authStringEnd variable

The method will return a JsonObject with your response

public JSONObject getAllTypes() throws JSONException, IOException {
        String url = "/api/atlas/types";
        String authString = name + ":" + password;
        String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
        javax.ws.rs.client.Client client = ClientBuilder.newClient();
        WebTarget webTarget = client.target(host + url);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header("Authorization", "Basic " + authStringEnc);

        Response response = invocationBuilder.get();
        String output = response.readEntity(String.class
        );

        System.out.println(response.toString());
        JSONObject obj = new JSONObject(output);

        return obj;
    }
3

Just make an http request to the required URL with correct query string, or request body.

For example you could use java.net.HttpURLConnection and then consume via connection.getInputStream(), and then covnert to your objects.

In spring there is a restTemplate that makes it all a bit easier.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
3

If you also need to convert that xml string that comes as a response to the service call, an x object you need can do it as follows:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class RestServiceClient {

// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) throws ParserConfigurationException,
SAXException {

try {

URL url = new URL(
    "http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
    + conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
    (conn.getInputStream())));

String output;

Ciudades ciudades = new Ciudades();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println("12132312");
System.err.println(output);

DocumentBuilder db = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));

Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
    .getElementsByTagName("ciudad");

for (int i = 0; i < nodes.getLength(); i++) {
    Ciudad ciudad = new Ciudad();
    Element element = (Element) nodes.item(i);

    NodeList name = element.getElementsByTagName("idCiudad");
    Element element2 = (Element) name.item(0);

    ciudad.setIdCiudad(Integer
        .valueOf(getCharacterDataFromElement(element2)));

    NodeList title = element.getElementsByTagName("nomCiudad");
    element2 = (Element) title.item(0);

    ciudad.setNombre(getCharacterDataFromElement(element2));

    ciudades.getPartnerAccount().add(ciudad);
}
}

for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}

conn.disconnect();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}

Note that the xml structure that I expected in the example was as follows:

<ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>
2

Look at Jersey. Again, REST is all about the data. And a tutorial here

Pradeep Pati
  • 5,779
  • 3
  • 29
  • 43
1

JAX-RS but you can also use regular DOM that comes with standard Java

amphibient
  • 29,770
  • 54
  • 146
  • 240
1

From your question its not clear whether you are using any frameworks.For REST you will be getting an WADL & Apache CXF recently added support for WADL-first development of REST services.Please go through http://cxf.apache.org/docs/index.html

Prabhath kesav
  • 428
  • 3
  • 6
  • 21
1

You can able to consume a Restful Web service in Spring using RestTemplate.class.

Example :

public class Application {

    public static void main(String args[]) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> call= restTemplate.getForEntity("http://localhost:8080/SpringExample/hello",String.class);
        System.out.println(call.getBody())
    }

}

Reference

Community
  • 1
  • 1
Joby Wilson Mathews
  • 10,528
  • 6
  • 54
  • 53
0

Apache Http Client APIs are very commonly used for calling HTTP Rest services.

Here is one of example of consuming HTTP GET call.

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;

public class CallHTTPGetService {

public static void main(String[] args) throws ClientProtocolException, IOException {


    HttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest httpUriRequest = new HttpGet("URL");

    HttpResponse response = client.execute(httpUriRequest);
    System.out.println(response);

}
}

Use following maven dependency if using Maven project.

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.1</version>
    </dependency>
Red Boy
  • 5,429
  • 3
  • 28
  • 41