如何在java中进行rest api调用并映射响应对象?

时间:2018-06-15 13:10:05

标签: java spring rest jira-rest-api

我正在开发我的第一个java程序,它会打电话给一个休息api(jira rest api,更具体)。

所以,如果我去我的浏览器并输入url = “http://my-jira-domain/rest/api/latest/search?jql=assignee=currentuser()&fields=worklog

我得到了当前用户的所有工作日志的响应(json)。 但我的问题是,我如何做我的java程序来做到这一点? 比如,连接到此URL,获取响应并将其存储在对象中?

我使用spring,有人知道如何使用它。 先谢谢你们。

我添加,我的代码在这里:

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是一个只有一些属性的简单类。

编辑, 我的全班:

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

此代码返回: org.springframework.http.converter.HttpMessageNotWritableException

任何人都知道为什么?

5 个答案:

答案 0 :(得分:2)

您只需要http客户端。它可以是例如RestTemplate(与spring相关,简单的客户端)或更高级,更可读的对我Retrofit(或您最喜欢的客户端)。

使用此客户端,您可以执行此类请求以获取JSON:

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

一般来说,在Java中映射beetwen JSON和对象/集合的方法是Jackson / Gson库。相反,他们可以快速检查你可以:

  1. 定义POJO对象:

    public class User implements Serializable {
    private String name;
    private String surname;
    // standard getters and setters
    }
    
  2. 使用RestTemplate的getForObject()方法。

    User user = restTemplate.getForObject(userResourceUrl + "/userId", User.class);
    
  3. 要获得有关使用RestTemplate和Jackson的基本知识,我建议您使用baeldung中的精彩文章:

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

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

答案 1 :(得分:0)

由于您使用的是Spring,因此您可以查看RestTemplate项目的spring-web

使用RestTemplate进行的简单休息呼叫可以是:

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

答案 2 :(得分:0)

问题可能是因为序列化。使用字段来定义适当的模型。这应该可以解决你的问题。

对于一个新手来说可能不是一个更好的选择,但我觉得spring-cloud-feign帮助我保持代码清洁。

基本上,您将拥有一个用于调用JIRA api的界面。

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

在你的控制器中,你只需要注入JiraClient并调用方法

  

jiraClient.search();

它还提供了传递headers的简便方法。

答案 3 :(得分:0)

我回来并提出解决方案(:

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

}

上面的代码有效,但有人可以向我解释这两行吗?

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

而且,这是一个很好的代码? thx(:

答案 4 :(得分:0)

您可以使用我的RESTUtil类来调用Java应用程序中的任何REST服务。参见https://github.com/gajeralalji/JAVA-REST-Client/wiki

相关问题