简体   繁体   中英

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

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 ?

All you need is http client. It could be for example RestTemplate (related to spring, easy client) or more advanced and a little more readably 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

Since you are using Spring you can take a look at RestTemplate of spring-web project.

A simple rest call using the RestTemplate can be:

RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos";
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

The issue could be because of the serialization. Define a proper Model with fields coming to the response. That should solve your problem.

May not be a better option for a newbie, but I felt spring-cloud-feign has helped me to keep the code clean.

Basically, you will be having an interface for invoking the JIRA api.

@FeignClient("http://my-jira-domain/")
public interface JiraClient {  
    @RequestMapping(value = "rest/api/latest/search?jql=assignee=currentuser()&fields=", method = GET)
    JiraWorklogResponse search();
}

And in your controller, you just have to inject the JiraClient and invoke the method

jiraClient.search();

And it also provides easy way to pass the headers .

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 (:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM