简体   繁体   English

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

[英]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). 我正在开发我的第一个java程序,它将打电话给一个休息api(jira rest api,更具体)。

So, if i go to my browser and type the url = " http://my-jira-domain/rest/api/latest/search?jql=assignee=currentuser()&fields=worklog " 所以,如果我去我的浏览器并输入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. 我得到了当前用户的所有工作日志的响应(json)。 But my problem is, how i do my java program to do this ? 但我的问题是,我如何做我的java程序来做到这一点? Like,connect to this url, get the response and store it in a object ? 比如,连接到此URL,获取响应并将其存储在对象中?

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

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 此代码返回:org.springframework.http.converter.HttpMessageNotWritableException

Anyone knows why ? 谁知道为什么?

All you need is http client. 您只需要http客户端。 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). 它可以是例如RestTemplate(与spring,easy客户端相关)或更高级,更可读的对我来说Retrofit(或您最喜欢的客户端)。

With this client you can execute requests like this to obtain JSON: 使用此客户端,您可以执行此类请求以获取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. 通常推荐的方式来映射beetwen JSON和Java中的对象/集合是Jackson / Gson库。 Instead them for quickly check you can: 相反,他们可以快速检查你可以:

  1. Define POJO object: 定义POJO对象:

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

     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: 要获得有关使用RestTemplate和Jackson的基本知识,我建议您使用baeldung的文章:

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

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

Since you are using Spring you can take a look at RestTemplate of spring-web project. 由于您使用的是Spring您可以查看spring-web项目的RestTemplate

A simple rest call using the RestTemplate can be: 使用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));

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. 对于一个新手来说可能不是一个更好的选择,但我觉得spring-cloud-feign帮助我保持代码干净。

Basically, you will be having an interface for invoking the JIRA api. 基本上,您将拥有一个用于调用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并调用该方法

jiraClient.search(); 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 (: 谢谢 (:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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