Phant
Phant

Reputation: 83

REST call in Java

I have a few questions about a specific REST call I'm making in JAVA. I'm quite the novice, so I've cobbled this together from several sources. The call itself looks like this:

String src = AaRestCall.subTrackingNum(trackingNum);

The Rest call class looks like this:

public class AaRestCall {
public static String subTrackingNum (Sting trackingNum) throws IOException {
    URL url = new URL("https://.../rest/" + trackingNum);
    String query = "{'TRACKINGNUM': trackingNum}";

    //make connection
    URLConnection urlc = url.openConnection();

    //use post mode
    urlc.setDoOutput(true);
    urlc.setAllowUserInteraction(false);

    //send query
    PrintStream ps = new PrintStream(urlc.getOutputStream());
    ps.print(query);
    ps.close();

    //get result
    BufferedReader br = new BufferedReader(new InputStreamReader(urlc
        .getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line=br.readLine())!=null) {
        sb.append(line);
    }
    br.close();

    return sb.toString();
}
}

Now, I have a few questions on top of the what is wrong with this in general.

1) If this rest call is returning a JSON object, is that going to get screwed up by going to a String?

2) What's the best way to parse out the JSON that is returning?

3) I'm not really certain how to format the query field. I assume that's supposed to be documented in the REST API?

Thanks in advance.

Upvotes: 3

Views: 518

Answers (3)

Raffaele
Raffaele

Reputation: 20885

REST is a pattern applied on top of HTTP. From your questions, it seems to me that you first need to understand how HTTP (and chatty socket protocols in general) works and what the Java API offers for deal with it.

You can use whatever Json library out there to parse the HTTP response body (provided it's a 200 OK, that you need to check for, and also watch out for HTTP redirects!), but it's not how things are usually built.

If the service exposes a real RESTful interface (opposed to a simpler HTTP+JSON) you'll need to use four HTTP verbs, and URLConnection doesn't let you do so. Plus, you'll likely want to add headers for authentication, or maybe cookies (which in fact are just HTTP headers, but are still worth to be considered separately). So my suggestion is building the client-side part of the service with the HttpClient from Apache commons, or maybe some JAX-RS library with client support (for example Apache CXF). In that way you'll have full control of the communication while also getting nicer abstractions to work with, instead of consuming the InputStream provided by your URLConnection and manually serializing/deserializing parameters/responses.

Regarding the bit about how to format the query field, again you first need to grasp the basics of HTTP. Anyway, the definite answer depends on the remote service implementation, but you'll face four options:

  1. The query string in the service URL
  2. A form-encoded body of your HTTP request
  3. A multipart body of your HTTP request (similar to the former, but the different MIME type is enough to give some headache) - this is often used in HTTP+JSON services that also have a website, and the same URL can be used for uploading a form that contains a file input
  4. A service-defined (for example application/json, or application/xml) encoding for your HTTP body (again, it's really the same as the previous two points, but the different MIME encoding means that you'll have to use a different API)

Upvotes: 2

folkol
folkol

Reputation: 4883

I think that you should use a REST client library instead of writing your own, unless it is for educational purposes - then by all means go nuts!

The REST service will respond to your call with a HTTP response, the payload may and may not be formatted as a JSON string. If it is, I suggest that you use a JSON parsing library to convert that String into a Java representation.

And yes, you will have to resort to the particular REST API:s documentation for details.

P.S. The java URL class is broken, use URI instead.

Upvotes: 1

Deepak Bala
Deepak Bala

Reputation: 11185

Oh my. There are a couple of areas where you can improve on this code. I'm not even going to point out the errors since I'd like you to replace the HTTP calls with a HTTP client library. I'm also unaware of the spec required by your API so getting you to use the POST or GET methods properly at this level of abstraction will take more work.

1) If this rest call is returning a JSON object, is that going to get screwed up by going to a String?

No, but marshalling that json into an obect is your job. A library like google gson can help.

2) What's the best way to parse out the JSON that is returning?

I like to use gson like I mentioned above, but you can use another marshal/unmarhal library.

3) I'm not really certain how to format the query field. I assume that's supposed to be documented in the REST API?

Yes. Take a look at the documentation and come up with java objects that mirror the json structure. You can then parse them with the following code.

gson.fromJson(json, MyStructure.class);

Http client

Please take a look at writing your HTTP client using a library like apache HTTP client which will make your job much easier.

Testing

Since you seem to be new to this, I'd also suggest you take a look at a tool like Postman which can help you test your API calls if you suspect that the code you've written is faulty.

Upvotes: 1

Related Questions