I am solving a requirement. I am using the springboot framework. Now there is an interface that passes in the parameter url. This url is a network file address. After receiving the request, the interface uses its own network to request the network file and returns it to the client in real time. , php’s readfile function can solve the problem, but is there such a solution in the java language? What I need is to return to the client in real time, instead of reading all and returning to the client
@Controller
@Api(tags = "test")
@RequestMapping("/test")
@CrossOrigin
public class TestController {
@RequestMapping(value = "/get", method = RequestMethod.POST)
@ApiOperation(value = "get")
public ResponseEntity<FileSystemResource> test() throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{"123": 1}");
Request request = new Request.Builder()
.url("https://github.com/xujimu/ios_super_sign/archive/refs/heads/master.zip")
.method("GET", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
}
}
2
Answers
I solved the problem by java's URL class
You can use
ResponseEntity<StreamingResponseBody>
for this.You have choose which content-type you want to return. We ended up with
produces = MediaType.APPLICATION_NDJSON_VALUE
.We had to modify the way we did rest request by changing from
RestClient to
WebClient`:When we finally got this to work, it works really well 🙂
You can see some other examples on https://www.baeldung.com/spring-mvc-sse-streams.