In this article we will understand how we can fetch data from REST API in java without using any third party library.
Here we are using REST API related to Users information
(URL : https://jsonplaceholder.typicode.com/users) for demo purpose. below you can see API response.
Now Below is our Java code that will fetch this data in String format and print it.
- Here using the "url.openConnection()" we creates a Connection object.
- after this we can update request properties like requestMethod in Connection object. here we updated requestMethod as "Get".
- Now the connection to remote object (REST API) is created through "connect()" method.
- using method "getResponseCode()" we can get the response code of REST API. It can be 200(OK), 404 (Not Found), etc.
- Now if our response code is OK(200) , we can fetch the response using "getInputStream()" method of Connection as shown in the code snippet (line number 19 to 25).
Below is the output:
Now if you just want to fetch information of a particular user id then you can modify code as shown below.
- Here in above code snippet we are fetching user details of user id "2"
Below is the output:
Now to parse this data, you can create your own JSON parser or use any third party JSON parser library.
Note : Please comment below for any improvement , suggestions, regarding any wrong information present in this article. We will improve it so that only right information available in this article.
Some of other popular article you can give it a try.
- Collection framework in Java
- Dependency Injection in spring boot
- Tomcat installation in linuxlite-4.8
- Program, Process and Thread




Comments
Post a Comment