Get JSON from REST API in Java

I am trying to get JSON data from my TeamCity project from java.

The problem is, I don't know how and I couldn't find any examples for java.

I hope someone could help me!

0
1 comment

Hello, 

Here's a small example showing how to get JSON data from the Rest API in Java, picking a scenario from the common use cases in the REST API Documentation for the sake of the demonstration. The example will retrieve user information.
 
  1. According to the REST API Documentation, to get the user's data you need to use the following endpoint:
  • http://<TeamCity Server host>:<port>/app/rest/users
  • Using this url in the browser, you get a response like this:
  1. <users count="2">
    <user username="USER1" name="user1 name" id="1" href="/app/rest/users/id:1"/>
    <user username="USER2" name="user2 name" id="2" href="/app/rest/users/id:2"/>
    </users>
  • With this response in mind, you can create the following classes to deserialize the response of the webservice:
  1.  public class TCUserResponse {        
    int count;       
    ArrayList<TCUser> user = new ArrayList<TCUser>();       

    public TCUserResponse() {
    }

    public TCUserResponse(int count, ArrayList<TCUser> user) {
    this.count = count;
    this.user = user;
    }

    public int getCount() {
    return count;
    }

    public void setCount(int count) {
    this.count = count;
    }

    public ArrayList<TCUser> getUser() {
    return user;
    }

    public void setUser(ArrayList<TCUser> user) {
    this.user = user;
    }
    }
  2. public class TCUser {
            String username;
            String name;
            int id;
            String href;

           public String getUsername() {
    return username;
    }

    public void setUsername(String username) {
    this.username = username;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    public String getHref() {
    return href;
    }

    public void setHref(String href) {
    this.href = href;
    }

    public TCUser(String username, String name, int id, String href) {
    this.username = username;
    this.name = name;
    this.id = id;
    this.href = href;
    }

    @Override
    public String toString() {
    return "TCUser{" +
    "username='" + username + '\'' +
    ", name='" + name + '\'' +
    ", id=" + id +
    ", href='" + href + '\'' +
    '}';
    }
    }
  • In this example Gson is used to convert the information you get into a Java object. You can find information about how to install it and use it here.
  • Finally in the java main class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Iterator;
import com.google.gson.Gson;

    public static void main(String[] args) {

        String user = "<TEAMCITY USER>";
        String pass = "<TEAMCITY USER PASSWORD>";
        String TeamCityRestAPIEndpoint = "<TEAMCITY ENDPOINT>";
        String usersService = "/users";
        TCUserResponse userList = null;

        try {
            //Prepare Basic Auth

            String auth = user + ":" + pass;
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
            String authHeaderValue = "Basic " + new String(encodedAuth);

            //Prepare URL to fetch TeamCity data
            String usersURL = TeamCityRestAPIEndpoint +usersService;
            URL url = new URL(usersURL);

            //Set connection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Authorization", authHeaderValue);
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : "
                        + conn.getResponseCode());
            }

            //Get and process response
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String output;
            while ((output = br.readLine()) != null) {
                //This is the response from the server
                System.out.println("This is the response from the server");
                System.out.println(output);

                //From here you can deserialize the JSON to your object in Java
                Gson gson = new Gson();
                userList = gson.fromJson(output, TCUserResponse.class);
            }

            // To output the data we deserialized to our object
            Iterator<TCUser> iter = userList.getUser().iterator();

            System.out.println("This is the data we got after deserialization to our object");
            while (iter.hasNext()) {
                System.out.println(iter.next().toString());
            }
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }


}
 
When you run this example, the output would be something like this:
 
This is the response from the server
{"count":2,"user":[{"username":"USER1","name":"User1 name","id":1,"href":"/app/rest/users/id:1"},{"username":"USER2","name":"User2 name","id":2,"href":"/app/rest/users/id:2"}]}
This is the data we got after deserialization to our object
TCUser{username='USER1', name='User1 name', id=1, href='/app/rest/users/id:1'}
TCUser{username='USER2', name='User2 name', id=2, href='/app/rest/users/id:2'}


Process finished with exit code 0
 
Note: You can read more about TeamCity REST authentication here.
 
I hope this small example is enough to get you going. Please let me know if you have any more questions.
0

Please sign in to leave a comment.