REST call in Java

I have a few questions about the specific REST call I am making in JAVA. I'm pretty new to it, so I've compiled 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 about what is wrong with this at all.

1) If this residual call returns a JSON object, will it get confusing going to the string?

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

3) I'm not sure how to format the request field. I'm guessing it should be documented in the REST API?

Thanks in advance.

+3


source to share


3 answers


REST is a pattern applied over HTTP. From your questions, it seems to me that you first need to understand how the HTTP protocols (and chatty socket in general) work and what the Java API offers to solve it.

You can use any Json library to parse the HTTP response body (assuming it's 200 OK, which is what you need to check and also watch out for the HTTP redirect!), But that's not how things are usually built.

If the service provides a real RESTful interface (as opposed to plain HTTP + JSON), you will need to use four HTTP verbs, and URLConnection will not let you do that. Also, you will most likely want to add headers for authentication, or maybe cookies (which are really just HTTP headers, but still worth considering separately). So my suggestion is to build a client side of the service using the HttpClient from the Apache community, or maybe a client-side JAX-RS library (like Apache CXF). This way you will have complete control over the communication and also get nicer abstractions to work with, instead of consuming the InputStream provided by your URLConnection and the parameters / responses to manual serialization / deserialization.



As for the bit about how to format the request field, you first need to understand the basics of HTTP. In any case, the definite answer depends on the implementation of the remote service, but you will be faced with four options:

  • Query string in the service url
  • A body encoded in the form of your HTTP request.
  • Multipart object of your HTTP request (similar to the first one, but a 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 to load form containing input file

  • A specific service (for example, application/json

    or application/xml

    ) the encoding for your HTTP body (again, this is indeed the same as the previous two dots, but a different MIME encoding means you will need to use a different API)
+2


source


Oh, my. There are several areas where you can improve this code. I'm not even going to point out the errors as I want you to replace the HTTP calls with the HTTP client library. I also don't know the specification your API requires, so more work will be required at this level of abstraction to get you to use the POST or GET methods correctly.

1) If this rest call returns a JSON object, will this get screwed up going to string?

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

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

I like to use gson as I mentioned above, but you can use a different marshal / non-marginal library.

3) I'm not sure how to format the request field. I guess which should be documented in the REST API?



Yes. Take a look at the documentation and come up with java objects that reflect the json structure. Then you can parse them with the following code.

gson.fromJson(json, MyStructure.class);

Http client

Note that you write your HTTP client using a library like apache HTTP client , which will make your work easier.

Testing

Since you seem to be new to this, I also suggest you take a look at a tool like Postman that can help you validate your API calls if you suspect the code you wrote is faulty.

+1


source


I think you should be using the REST client library instead of writing your own, unless it's for educational purposes - then nuts for sure!

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

And yes, you need to refer to the specific REST API documentation: for details.

PS The java url class is broken, use URI instead.

+1


source







All Articles