有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我目前正在开发我的第一个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;
}

此代码正在返回: 组织。springframework。http。转换器。HttpMessageWritableException

有人知道为什么吗


共 (4) 个答案

  1. # 1 楼答案

    因为您使用的是Spring,所以可以查看spring-web项目的RestTemplate

    使用^{}的简单rest调用可以是:

    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. # 2 楼答案

    我回来了,带着一个解决方案(:

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

  3. # 3 楼答案

    问题可能是因为序列化。定义一个合适的模型,并在响应中加入字段。这应该能解决你的问题

    对于新手来说,这可能不是一个更好的选择,但我觉得spring cloud Faign帮助我保持了代码的整洁

    基本上,您将拥有一个调用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. # 4 楼答案

    您只需要http客户端。例如,它可以是RestTemplate(与spring、easy client相关),也可以是更高级、可读性更强的版本(或您最喜欢的客户端)

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

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

    通常推荐在Java中映射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