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

Estudeiro picture Estudeiro · Jun 15, 2018 · Viewed 22k times · Source

I'm currently developing my first java program who'll make a call to a rest api(jira rest api, to be more especific).

So, if i go to my browser and type the url = "http://my-jira-domain/rest/api/latest/search?jql=assignee=currentuser()&fields=worklog"

I get a response(json) with all the worklogs of the current user. But my problem is, how i do my java program to do this ? Like,connect to this url, get the response and store it in a object ?

I use spring, with someone know how to this with it. Thx in advance guys.

Im adding, my code here:

RestTemplate restTemplate = new RestTemplate();
String url;
url = http://my-jira-domain/rest/api/latest/search/jql=assignee=currentuser()&fields=worklog
jiraResponse = restTemplate.getForObject(url,JiraWorklogResponse.class);

JiraWorkLogResponse is a simple class with some attributes only.

Edit, My entire class:

@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 getWorkLog() {


    RestTemplate restTemplate = new RestTemplate();
    String url;
    JiraProperties jiraProperties = null;


    url = "http://my-jira-domain/rest/api/latest/search?jql=assignee=currentuser()&fields=worklog";

    ResponseEntity<JiraWorklogResponse> jiraResponse;
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders = this.createHeaders();


    try {
        jiraResponse = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(httpHeaders),JiraWorklogResponse.class);



    }catch (Exception e){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }

    return ResponseEntity.status(HttpStatus.OK).body(jiraResponse);

}


private HttpHeaders createHeaders(){
    HttpHeaders headers = new HttpHeaders(){
        {
            set("Authorization", "Basic something");
        }
    };
    return headers;
}

This code is returning : org.springframework.http.converter.HttpMessageNotWritableException

Anyone knows why ?

Answer

B.Ohara picture B.Ohara · Jun 15, 2018

All you need is http client. It could be for example RestTemplate (related to spring, easy client) or more advanced and a little more readable for me Retrofit (or your favorite client).

With this client you can execute requests like this to obtain JSON:

 RestTemplate coolRestTemplate = new RestTemplate();
 String url = "http://host/user/";
 ResponseEntity<String> response
 = restTemplate.getForEntity(userResourceUrl + "/userId", String.class);

Generally recommened way to map beetwen JSON and objects/collections in Java is Jackson/Gson libraries. Instead them for quickly check you can:

  1. Define POJO object:

    public class User implements Serializable {
    private String name;
    private String surname;
    // standard getters and setters
    }
    
  2. Use getForObject() method of RestTemplate.

    User user = restTemplate.getForObject(userResourceUrl + "/userId", User.class);
    

To get basic knowledge about working with RestTemplate and Jackson , I recommend you, really great articles from baeldung:

http://www.baeldung.com/rest-template

http://www.baeldung.com/jackson-object-mapper-tutorial