标签: spring-rest

通过Spring rest模板下载大文件

服务器代码:

@POST
@Path("reportDownload")
@Consumes(MediaType.APPLICATION_JSON)
public Response generateReport(QueryData queryData) {
     File file = new File("report.xlsx") // large file
     StreamingOutput stream = new FileStreamingOutput(file) ; 
        return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM)
            .header("filename" , file.getName())
            .build();
}
Run Code Online (Sandbox Code Playgroud)

客户代码:

使用以下代码,我可以将文件下载到一定的限制。获取大文件的内存堆错误。

final String uri = buildUri("/reportGenerate/reportDownload");

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(read_timeout);
    factory.setConnectTimeout(connection_timeout);

    RestTemplate restTemplate = new RestTemplate(factory);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.APPLICATION_OCTET_STREAM);
    headers.setAccept(mediaTypeList);
    HttpEntity entity = new HttpEntity(queryData, headers);
    ResponseEntity<byte[]> data = restTemplate.exchange(uri, HttpMethod.POST, entity, byte[].class);
    HttpHeaders responseHeader = data.getHeaders(); …
Run Code Online (Sandbox Code Playgroud)

java spring resttemplate spring-rest

4
推荐指数
1
解决办法
9290
查看次数

Spring RestController POST 400 Bad Request

我有一个Spring RestController,尽管在Chrome开发者工具中发现了正确的数据,但任何尝试发布到它都会返回400 Bad Request.@Valid注释正在将其踢出,因为根本没有填充ParameterDTO对象.

我的控制器

@RestController
@RequestMapping(path = "/api/parameters", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public class ParameterResource {

    private final ParameterService parameterService;

    @Autowired
    public ParameterResource(ParameterService parameterService) {
        this.parameterService = parameterService;
    }

    @GetMapping
    public ResponseEntity<?> getParameters(@RequestParam(value = "subGroupId", required = false) Integer subGroupId) {
        if (subGroupId != null) {
            return ResponseEntity.ok(parameterService.getParameters(subGroupId));
        }
        return ResponseEntity.ok(parameterService.getParameters());
    }

    @PostMapping
    public ResponseEntity<?> createParameter(@Valid ParameterDTO parameterData) {
        int id = parameterService.saveParameter(parameterData);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(id).toUri();
        return ResponseEntity.created(uri).build();
    }

    @GetMapping(path = "/levels")
    public ResponseEntity<?> getParameterLevels() …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-restcontroller spring-rest

4
推荐指数
1
解决办法
3340
查看次数

错误:对于 JPA 中的 GeneratedValue,给定的 id 不能为 null

我的对象:

@Entity
@Table(name="user")
public class User {
    @Id
    @Column(name="uid")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

  //more code
 }
Run Code Online (Sandbox Code Playgroud)

当我POST user JSON没有时uid,我收到错误,因为给定的 id 不能为 null。这不应该是这种情况,而uid应该由数据库生成。请指出我遗漏了什么。

JSON:

{
"email": "john@mail.com",
"name": "John Doe",
"phone": "98-765-4445"
}
Run Code Online (Sandbox Code Playgroud)

错误:

{
"timestamp": 1501058952038,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!",
"path": "/api/user/"
}
Run Code Online (Sandbox Code Playgroud)

java rest jpa spring-boot spring-rest

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

Spring Boot中使用自定义令牌进行身份验证

我需要保护我的 Spring Boot 应用程序,这就是我所拥有的:

  1. 一个 Spring Boot 应用程序,公开了一些 REST API。
  2. 与公开的 api 通信的前端。
  3. 前端发送用于身份验证的自定义身份验证令牌。
  4. 存储自定义身份验证令牌的数据库。

因此,本质上我的前端将向我的 Spring Boot 应用程序发送一个休息请求以及身份验证令牌,并且我的 Spring Boot 应用程序将查询数据库以查看身份验证令牌是否有效。

此身份验证应该适用于我的 Spring Boot 应用程序中的所有控制器。有没有一种方法可以默认为每个休息请求执行此操作,而无需在每个控制器中显式放置身份验证?

我了解 Spring Boot Web 安全功能,但没有足够的信息来说明如何将这些功能与自定义令牌一起使用。

spring spring-security spring-boot spring-rest

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

@PostMapping 和 @PutMapping 获取空值

我创建了一个简单的 Spring REST 服务(POST、PUT)。但是当我从邮递员调用此服务时,值存储在null中。

学生Pojo班

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.hateoas.ResourceSupport;

@SuppressWarnings("serial")
@Entity
@Table(schema="fishpool")
public class Student extends ResourceSupport implements Serializable {

@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long sId;
private String name;
private String email;

public Student() {

}

public Student(Long sId, String name, String email) {
    this.sId = sId;
    this.name = name;
    this.email = email;
}

public Long getsId() {
    return sId;
}

public void setsId(Long sId) {
    this.sId …
Run Code Online (Sandbox Code Playgroud)

spring json spring-mvc spring-boot spring-rest

4
推荐指数
1
解决办法
9065
查看次数

是否可以在 Spring 控制器中拆分请求参数?

我有一个请求,例如:

example.com/search?sort=myfield1,-myfield2,myfield3
Run Code Online (Sandbox Code Playgroud)

我想拆分这些参数以List<String>在控制器中绑定排序,或者具有以下字段的类List<SortParam>在哪里:(字符串)和(布尔值)。SortParamnameask

所以最终的控制器看起来像这样:

@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> search(@RequestParam List<String> sort) {

    //...
}
Run Code Online (Sandbox Code Playgroud)

或者

@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> search(@RequestParam List<SortParam> sort) {

    //...
}
Run Code Online (Sandbox Code Playgroud)

有办法制作吗?

更新:

标准的参数传递方式不能满足我的要求。即我无法使用sort=myfield1&sort=-myfield2&sort=myfield3. 我必须使用逗号分隔的名称。
另外,我确实明白我可以@RequestParam String sort在控制器中接受,然后在控制器内分割字符串sort.split(","),但它也不能解决上述问题。

java spring spring-mvc spring-restcontroller spring-rest

4
推荐指数
2
解决办法
9926
查看次数

如何配置spring的RestTemplate发出http2请求?

我有一个RestClient调用GET请求到spring服务(服务器),该服务器正在接受HTTP2请求,并且我得到302作为响应。如何使用spring RestTemplate发送Http2请求。

Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://example.com/static/mobile/get-token": unexpected end of stream on Connection{domain.com:443, proxy=DIRECT hostAddress=example.com cipherSuite=TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 protocol=http/1.1}; nested exception is java.io.IOException: unexpected end of stream on Connection{example.com:443, proxy=DIRECT hostAddress=example.com cipherSuite=TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 protocol=http/1.1}
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:732)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:680)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:600)
at com.domain.Sample.main(Sample.java:45)
Caused by: java.io.IOException: unexpected end of stream on Connection{example.com:443, proxy=DIRECT hostAddress=example.com cipherSuite=TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 protocol=http/1.1}
    at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:205)
    at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at …
Run Code Online (Sandbox Code Playgroud)

spring resttemplate spring-boot microservices spring-rest

4
推荐指数
1
解决办法
1617
查看次数

如何使用 ExceptionHandler 在 Spring Boot Rest 中包装 Path Not Found 异常?

我正在使用 Spring Boot 和 Spring Rest 示例。在此示例中,我传递自定义标头,如果该值有效,则端点被成功调用,如果自定义标头值不正确,则我得到以下响应,我想将其包装到使用 ExceptionHandler 将其显示给最终用户@ControllerAdvice

注意:我浏览了Spring mvc - 如何将所有错误的请求映射到单个方法,但在我的例子中,我根据 CustomHeader 做出决定。

{
    "timestamp": "2020-01-28T13:47:16.201+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/employee-data/employee-codes"
}
Run Code Online (Sandbox Code Playgroud)

控制器

@Operation(summary = "Find Employee")
@ApiResponses(value = { @ApiResponse(code = 200, message = "SUCCESS"),
        @ApiResponse(code = 500, message = "Internal Server Error") })
@Parameter(in = ParameterIn.HEADER, description = "X-Accept-Version", name = "X-Accept-Version", 
        content = @Content(schema = @Schema(type = "string", defaultValue = "v1", 
        allowableValues = {HeaderConst.V1}, implementation …
Run Code Online (Sandbox Code Playgroud)

spring spring-boot spring-rest

4
推荐指数
1
解决办法
8243
查看次数

为什么我的集成测试抱怨 Spring Boot 中缺少 RestTemplate 接线?

为什么我的集成测试抱怨缺少RestTemplate接线Spring Boot

我可以做什么来修复这个集成测试?

此外,这是集成测试还是单元测试?根据我的理解,这个测试是调用一个模拟服务器,它是一个外部实体(在被测类之外),因此它是一个集成测试。我的理解正确吗?

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath />
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
Run Code Online (Sandbox Code Playgroud)

src/main/java/RestTemplateConfig.java

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        Collection<ClientHttpRequestInterceptor> clientHttpRequestInterceptors = List.of(new RestTemplateInterceptor());
        return new RestTemplateBuilder()
                .errorHandler(new CustomClientErrorHandler())
                .interceptors(clientHttpRequestInterceptors)
                .build();
    }
}
Run Code Online (Sandbox Code Playgroud)

src/main/java/AccountService.java

@Service
@Log4j2
public class AccountService {

    @Autowired
    private RestTemplate restTemplate;

    public Account getAccount() throws Exception {
        //build uri
        URI uri = new URI(http://api.demo.com/api/account)
        log.info("uri: " + uri); …
Run Code Online (Sandbox Code Playgroud)

spring spring-test spring-boot spring-rest spring-resttemplate

4
推荐指数
1
解决办法
3041
查看次数

@EnableWebMvc 在数组格式中显示日期

我们在 Spring Boot 上有两个应用程序。第一个是基于 Spring Rest api,第二个是基于 Spring MVC。

由于某些业务原因,我们已经合并了这两个应用程序,因为上下文相同,并且除了 java.time.LocalDateTime 格式化(由 Spring 在 REST API 上自动执行)之外,一切都工作正常。之前它将 LocalDateTime 格式化为“2018-08-30T18:13:24”,但合并后显示为 [ 2018, 08, 30, 18, 13, 24 ],

我发现 @EnableWebMVC 注释是罪魁祸首,但删除该注释后,web-mvc 页面不起作用。

我应该怎么做才能以 ISO(字符串)格式显示日期并查看解析器和 jsp 页面正常工作?

请帮忙谢谢。

java spring spring-mvc spring-boot spring-rest

4
推荐指数
1
解决办法
2848
查看次数