标签: spring-rest

使用Spring RestTemplate时,REST POST可以正常使用POSTMAN,但是异常

我正在编写一个Rest客户端来使用Spring RestTemplate发布JSON数据.在正文中使用POSTMAN和跟随JSON数据获得正确的响应 -

{
    "InCode":"test",
    "Name":"This is  test",
    "Email":"test@gmail.com",
    "Id":18,
}
Run Code Online (Sandbox Code Playgroud)

但是,当尝试使用Spring RestTemplate按如下方式命中REST API时

ResponseEntity<String> response = restTemplate.exchange(baseUrl,
                HttpMethod.POST, getHeaders(), String.class);

private HttpEntity<?> getHeaders() throws JSONException {
JSONObject request = new JSONObject();
        request.put("Email", "test@gmail.com");
        request.put("Id", "18");
        request.put("Name", "This is  test");
        request.put("InCode", "test");

        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        return new HttpEntity<>(request.toString(), headers);
        }
Run Code Online (Sandbox Code Playgroud)

我得到例外 -

11:52:56.808 [main] DEBUG o.s.web.client.RestTemplate - Created POST request for "http://server-test/platform/v4/org"
11:52:56.815 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
12:03:47.357 [main] DEBUG o.s.web.client.RestTemplate - …
Run Code Online (Sandbox Code Playgroud)

java rest spring resttemplate spring-rest

11
推荐指数
1
解决办法
3万
查看次数

如何使用spring记录RestTemplate请求和响应?

我正在使用springRestTemplate来执行GET查询.

如何在每个请求上自动将任何请求和响应数据记录到日志文件中?

java logging spring spring-rest

10
推荐指数
1
解决办法
2万
查看次数

@RestController方法默认似乎是Transactional,为什么?

使用Spring boot 1.3.1

我不明白为什么@RestController默认是Transactionnal.我在文档中没有发现任何这样的说法.

推动以下控制器中方法findOne()的事实是Transactionnal:

@RestController
@RequestMapping("/books")
public class BookController {

    @RequestMapping("/{id}")
    public Book findOne(@PathVariable Long id) {
        Book book = this.bookDao.findOneBookById(id);
        // following line
        // => triggers a select author0_.id as id1_0_0_ etc... // where author0_.id=?
        System.out.println(book.getAuthor().getFirstname()); 
        return book;
    }
}
Run Code Online (Sandbox Code Playgroud)

System.out.println的行(book.getAuthor().getFirstname()); 应该提出一个LazyInitiaizationFailure但这里它成功并触发一个作者的选择.所以方法findOne似乎是事务性的.使用eclipse调试器,我可以确定它确实是这一行触发了补充选择.但为什么那个方法是事务性的呢?

@Configuration
@ComponentScan(basePackageClasses = _Controller.class)
@Import(BusinessConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {
   // ... here the conf to setup Jackson Hibernate4Module
}

@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
@EntityScan(basePackageClasses = _Model.class)
@ComponentScan(basePackageClasses = { _Dao.class })
public class BusinessConfig { …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-rest

10
推荐指数
1
解决办法
5248
查看次数

使用spring RestTemplate在rest客户端上的最佳实践

我已经阅读了一些关于在java web应用程序中实现REST客户端的教程,这些教程使用SPRING来管理bean.

我发现的每个例子,每次执行REST请求时都会创建新的RestTemplate.

通常,Web应用程序使用singleton spring bean.

所以我想知道什么时候在Spring配置应用程序中使用RestTemplate的最佳做法是什么?
使用singleton RestTemplate?
在每个请求中创建RestTemplate.?

请告知并描述所有情况.

java rest spring resttemplate spring-rest

10
推荐指数
2
解决办法
9864
查看次数

Spring REST和PATCH方法

我正在使用SpringBoot和Spring REST.我想了解HTTP PATCH方法来更新我的Model的属性

是否有任何好的教程解释如何使其工作?

  • HTTP PATCH方法和正文发送
  • 控制器方法以及如何管理更新操作

spring spring-boot spring-rest

9
推荐指数
2
解决办法
2万
查看次数

如何调试在spring mvc rest中找不到的404资源?

我有一个示例spring rest mvc应用程序,它具有以下java代码:

SampleController.java

import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("sample")
public class SampleController {
        @RequestMapping(method = RequestMethod.GET, produces = "application/json")
        @ResponseBody
        public String getBatches()//@RequestParam(name = "name", required = true) String name)
        {
                return "Hello ";
        }
}
Run Code Online (Sandbox Code Playgroud)

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ved</groupId>
    <artifactId>platform</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>platform Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.2.1.RELEASE</spring.version>
        <jackson.version>2.6.2</jackson.version>
        <spring-boot.version>1.2.6.RELEASE</spring-boot.version>
        <filter.name>DEV</filter.name>
        <jersey.version>1.9</jersey.version>
        <base.directory>${basedir}</base.directory>
    </properties>
    <profiles>
        <profile>
            <id>local</id>
            <activation> …
Run Code Online (Sandbox Code Playgroud)

java maven spring-restcontroller spring-rest

9
推荐指数
2
解决办法
9125
查看次数

Spring Rest中@Context UriInfo的等价物是什么

我之前在Jersey和RESTEasy框架中工作过,现在我们将使用Spring Rest进行新项目,我不想将所有查询参数和矩阵参数作为参数传递给方法,通常我会用方法注释方法@Context UriInfo并将获取Jersey或RESTEasy Framework中我的方法中的所有参数以获取复杂参数.

我想知道@Context UriInfoSpring REST中是否有任何 类似于RESTEasy或Jersey Framework的内容.我想在方法中获取所有查询参数或矩阵参数和其他参数,而不是将它们作为方法中的参数传递.

jax-rs spring-mvc jersey resteasy spring-rest

9
推荐指数
1
解决办法
5594
查看次数

RestTemplate 与正文一起删除

我正在尝试对请求正文进行 DELETE,但我不断收到 400(错误请求)错误。当我在 swagger/postman 中执行此操作时,它成功删除了记录。但从 Java 代码来看我无法做到这一点

外部 API 的设计方式需要 body 和 URL。它无法改变。请让我知道如何删除带有请求正文的条目

public Person delete(Person person, String url, Map<String, String> uriVariables) throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();
        CustomObjectMapper mapper = new CustomObjectMapper();
        HttpEntity<Person> requestEntity = new HttpEntity<Person>(person);
        try {
            ResponseEntity<Person> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Person.class, uriVariables);
            return responseEntity.getBody();
        } catch (RestClientException e) {
            System.out.println(mapper.writeValueAsString(person));
            throw e;
        }
    }
Run Code Online (Sandbox Code Playgroud)

当出现异常时,我将获得 JSON 格式的 JSON 请求,并且在 Swagger/postman 中同样可以正常工作

我做了一些谷歌搜索,发现restTemplate在存在请求正文时存在删除问题。这篇文章没有帮助https://jira.spring.io/browse/SPR-12361有什么办法让它工作

java rest spring resttemplate spring-rest

9
推荐指数
2
解决办法
2万
查看次数

来自数据库的 Spring Boot 安全 REST 基本身份验证

我有一个问题,当我使用带有inMemoryAuthentication 的基本身份验证时,如下面的代码片段所示,它工作得很好。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user1").password("secret1").roles("USER")
                .and()
                .withUser("admin").password("123456").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
                .csrf().disable().headers().frameOptions().disable();
    }

}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用 get database 来获取将用于身份验证的用户数据时,它不起作用,只会发回 403 响应。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;//MySQL db via JPA

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username, password, 1 as enabled from user where username=?")
                .authoritiesByUsernameQuery("select username, role from user …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-boot spring-rest

9
推荐指数
1
解决办法
8704
查看次数

Spring WebClient - 错误底层 HTTP 客户端已完成但未发出响应

我有一个 spring boot(版本 2.1.8.RELEASE)rest 应用程序,其中包含来自控制器的以下邮件功能:

@PostMapping(value = "/sendMail1")
public  @ResponseBody EmailResponse sendMail1( @RequestBody EmailRequestDto emailRequestDto) {


        if (checkAllEmailAddValid(emailRequestDto)) {
            sendMailService.sendEmail(emailRequestDto);
            //return new ResponseEntity<>("Mail has been sent successfully", HttpStatus.OK);

            return new EmailResponse(HttpStatus.OK, "Mail has been sent successfully");
        } else {
            LOG.error("Email addresse provided is  invalid");
            //return new ResponseEntity<>("Email address provided is  invalid", HttpStatus.BAD_REQUEST);

            return new EmailResponse(HttpStatus.BAD_REQUEST, "Email address provided is  invalid");
        }

    }
Run Code Online (Sandbox Code Playgroud)

为服务类发送邮件的方法是:

@Override
    @Async("threadPoolExecutor")
    public void sendEmail(EmailRequestDto emailRequestDto) {




        LOG.debug("calling method sendMail");

        ...

        }
Run Code Online (Sandbox Code Playgroud)

我已在我的计算机上部署了上述其余服务,并可通过 url( http://localhost:9090/email-service/email/sendMail1 ) 进行访问。但是,当我使用 …

java spring-boot spring-rest

9
推荐指数
1
解决办法
9761
查看次数