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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50876331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:51:42  来源:igfitidea点击:

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

javaspringrestjira-rest-api

提问by Estudeiro

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 程序,该程序将调用 rest 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. 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 ?

我得到一个包含当前用户所有工作日志的响应(json)。但我的问题是,我如何做我的 java 程序来做到这一点?比如,连接到这个 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 ?

有谁知道为什么?

采纳答案by Estudeiro

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

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

回答by pleft

Since you are using Springyou can take a look at RestTemplateof spring-webproject.

既然你使用Spring,你可以看看RestTemplatespring-web项目。

A simple rest call using the RestTemplatecan 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));

回答by B.Ohara

All you need is http client. It could be for example RestTemplate (related to spring, easy client) or more advanced and a little more readable for me Retrofit (or your favorite client).

您只需要 http 客户端。例如,它可能是 RestTemplate(与 spring、easy client 相关)或更高级且对我来说更具可读性的 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 Hymanson/Gson libraries. Instead them for quickly check you can:

通常推荐的在 Java 中映射 beetwen JSON 和对象/集合的方法是 Hymanson/Gson 库。相反,他们可以快速检查:

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

To get basic knowledge about working with RestTemplate and Hymanson , I recommend you, really great articles from baeldung:

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

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

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

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

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

回答by Thiru

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.

它还提供了传递标头的简单方法。