Restful Call in Java

RESTful call in Java

If you are calling a RESTful service from a Service Provider (e.g Facebook, Twitter), you can do it with any flavour of your choice:

If you don't want to use external libraries, you can use java.net.HttpURLConnection or javax.net.ssl.HttpsURLConnection (for SSL), but that is call encapsulated in a Factory type pattern in java.net.URLConnection.
To receive the result, you will have to connection.getInputStream() which returns you an InputStream. You will then have to convert your input stream to string and parse the string into it's representative object (e.g. XML, JSON, etc).

Alternatively, Apache HttpClient (version 4 is the latest). It's more stable and robust than java's default URLConnection and it supports most (if not all) HTTP protocol (as well as it can be set to Strict mode). Your response will still be in InputStream and you can use it as mentioned above.


Documentation on HttpClient: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

How to make a rest api call in java and map the response object?

i'm back and with a solution (:

@Controller
@RequestMapping("/jira/worklogs")
public class JiraWorkLog {

private static final Logger logger = Logger.getLogger(JiraWorkLog.class.getName() );

@RequestMapping(path = "/get", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<JiraWorklogIssue> getWorkLog(@RequestParam(name = "username") String username) {

String theUrl = "http://my-jira-domain/rest/api/latest/search?jql=assignee="+username+"&fields=worklog";
RestTemplate restTemplate = new RestTemplate();

ResponseEntity<JiraWorklogIssue> response = null;
try {
HttpHeaders headers = createHttpHeaders();
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, JiraWorklogIssue.class);
System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
}
catch (Exception eek) {
System.out.println("** Exception: "+ eek.getMessage());
}

return response;

}

private HttpHeaders createHttpHeaders()
{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic encoded64 username:password");
return headers;
}

}

The code above works, but can someone explain to me these two lines ?

HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, JiraWorklogIssue.class);

And, this is a good code ?
thx (:

calling Restful Service from Java

UPDATE

as follow up with this: Can I do this way?? if the xml being returned
as 4
.....
If I am constructing a Person object, I believe this will choke up.
Can I just bind only the xml elements that I want? if Yes how can I do
that.

You could map this XML as follows:

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<Persons>
<NumberOfPersons>2</NumberOfPersons>
<Person>
<Name>Jane</Name>
<Age>40</Age>
</Person>
<Person>
<Name>John</Name>
<Age>50</Age>
</Person>
</Persons>

Persons

package forum7177628;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Persons")
@XmlAccessorType(XmlAccessType.FIELD)
public class Persons {

@XmlElement(name="Person")
private List<Person> people;

}

Person

package forum7177628;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

@XmlAccessorType(XmlAccessType.FIELD)
public class Person {

@XmlElement(name="Name")
private String name;

@XmlElement(name="Age")
private int age;

}

Demo

package forum7177628;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Persons.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();
Persons persons = (Persons) unmarshaller.unmarshal(new File("src/forum7177628/input.xml"));

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(persons, System.out);
}

}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Persons>
<Person>
<Name>Jane</Name>
<Age>40</Age>
</Person>
<Person>
<Name>John</Name>
<Age>50</Age>
</Person>
</Persons>

ORIGINAL ANSWER

Below is an example of calling a RESTful service using the Java SE APIs including JAXB:

String uri =
"http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
(Customer) jc.createUnmarshaller().unmarshal(xml);

connection.disconnect();

For More Information:

  • http://blog.bdoughan.com/2010/08/creating-restful-web-service-part-55.html

Java: How to make API call with data?

HTTP code 400 means a BAD REQUEST.

I can't access the endpoint you have shared but here is free online REST API which I am using for demonstrating ..

curl -X POST \
https://jsonplaceholder.typicode.com/posts \
-H 'cache-control: no-cache' \
-H 'postman-token: 907bbf75-73f5-703f-c8b6-3e1cd674ebf7' \
-d '{
"userId": 100,
"id": 100,
"title": "main title",
"body": "main body"
}'
  • -H = headers
  • -d = data

Sample Run:

[/c]$ curl -X POST \
> https://jsonplaceholder.typicode.com/posts \
> -H 'cache-control: no-cache' \
> -H 'postman-token: 907bbf75-73f5-703f-c8b6-3e1cd674ebf7' \
> -d '{
> "userId": 100,
> "id": 100,
> "title": "main title",
> "body": "main body"
> }'

% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 258 100 150 100 108 147 106 0:00:01 0:00:01 --:--:-- 192{
"{\n \"userId\": 100,\n \"id\": 100,\n \"title\": \"main title\",\n \"body\": \"main body\"\n }": "",
"id": 101
}

Java Code for the same is as follows:

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/octet-stream");
RequestBody body = RequestBody.create(mediaType, "{\n \"userId\": 100,\n \"id\": 100,\n \"title\": \"main title\",\n \"body\": \"main body\"\n }");
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts")
.post(body)
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "e11ce033-931a-0419-4903-ab860261a91a")
.build();

Response response = client.newCall(request).execute();

Another example of calling REST POST call with data ..

User user = new User();
user.setFirstName("john");
user.setLastName("Maclane");

ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("URL");
Response response = target.request().post(Entity.entity(user, <MEDIATYPE>));
//Read output in string format
System.out.println(response.getStatus());
response.close();

Here is the what your code looks like when I update it with my endpoints and payload.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

public class TestClass {

public static final String POST_URL = "https://jsonplaceholder.typicode.com/posts";

public static final String POST_DATA = "{\"userId\": 100,\"id\": 100,\"title\": \"main title\",\"body\": \"main body\"}";

public static void main(String[] args) throws Exception {
String[] details = {};
System.out.println(Arrays.toString(details));

URL line_api_url = new URL(POST_URL);
String payload = POST_DATA;

HttpURLConnection linec = (HttpURLConnection) line_api_url
.openConnection();
linec.setDoInput(true);
linec.setDoOutput(true);
linec.setRequestMethod("POST");
linec.setRequestProperty("Content-Type", "application/json");
linec.setRequestProperty("Authorization", "Bearer "
+ "1djCb/mXV+KtryMxr6i1bXw");

OutputStreamWriter writer = new OutputStreamWriter(
linec.getOutputStream(), "UTF-8");
writer.write(payload);

BufferedReader in = new BufferedReader(new InputStreamReader(
linec.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

In nutshell, check the API documentation and ensure the request payload is of correct format as 400 means BAD REQUEST.

How to consume REST in Java

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);
}
}
}

How to call a rest API which returns object of two different types

In that case, you probably may use it like that

ResponseEntity<Object> studentDetails = restTemplate.getForEntity(studentUrl, Object.class);

And then check for the response type and cast the result.



Related Topics



Leave a reply



Submit