【问题标题】:How to make a rest api call in java and map the response object?如何在java中进行rest api调用并映射响应对象?
【发布时间】:2018-11-25 08:14:56
【问题描述】:

我目前正在开发我的第一个 java 程序,它将调用一个 rest api(jira rest api,更具体一点)。

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

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

我使用弹簧,有人知道如何使用它。 提前谢谢各位。

我补充一下,我的代码在这里:

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

有人知道为什么吗?

【问题讨论】:

    标签: java spring rest jira-rest-api


    【解决方案1】:

    您所需要的只是 http 客户端。例如,它可能是 RestTemplate(与 spring、easy 客户端相关)或更高级且对我 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);
      

    要获得有关使用 RestTemplate 和 Jackson 的基本知识,我向您推荐来自 baeldung 的非常棒的文章:

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

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

    【讨论】:

    • 好的。但是您知道我如何使用 java 通过 http 标头传递我的凭据吗?因为可能其余的 api 会有一些身份验证。
    • 在身份验证的情况下更容易使用 RestTemplate.exchange 方法。只需检查第一个答案:stackoverflow.com/questions/15462128/…
    • 是的,现在越来越清楚了。在你的帮助下,我现在可以制作标题了,但是我收到了这个错误:“org.springframework.http.converter.HttpMessageNotWritableException”我要发布我的代码到目前为止
    • Estudeiro 看起来映射 beetwen http 响应存在问题,并且您对 JiraWorklogResponse 进行了分类。要验证它,您应该检查来自 Jira 的响应是否有可能映射到此类(这只是一个问题)。如果问题仍然存在,您应该提供异常的完整堆栈跟踪。
    【解决方案2】:

    由于您使用的是Spring,您可以查看RestTemplatespring-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));
    

    【讨论】:

    • 我正在使用这样的东西,我会在这里发布我的代码。你能解释一下为什么我们使用 (fooResourceUrl + "/1") 吗? “/1”是干什么用的?
    【解决方案3】:

    问题可能是由于序列化。定义一个适当的模型,其中包含响应的字段。这应该可以解决您的问题。

    对于新手来说可能不是更好的选择,但我觉得 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 的简便方法。

    【讨论】:

      【解决方案4】:

      我回来了,并且有一个解决方案(:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-30
        • 1970-01-01
        • 2021-11-15
        • 2019-09-24
        • 2019-07-22
        • 2018-12-05
        • 2013-07-20
        • 1970-01-01
        相关资源
        最近更新 更多