java前端请求代码_Java后端模拟前端请求

package com.example.hystrix.controller;

import org.springframework.core.io.FileSystemResource;

import org.springframework.util.LinkedMultiValueMap;

import org.springframework.util.MultiValueMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.client.RestTemplate;

import java.io.File;public classDemo{public voiduploadTest() {

String url= "http://localhost:8080/upload"; //上传的地址

String filePath = "D:/test/test.mp4";

RestTemplate rest= newRestTemplate();

FileSystemResource resource= new FileSystemResource(newFile(filePath));

MultiValueMap param = new LinkedMultiValueMap<>();

param.add("file", resource); //MultipartFile的名称

String restResult = rest.postForObject(url, param, String.class);

System.out.println(restResult);

}

}

另一种方式,代码片段:

MultiValueMap param = new LinkedMultiValueMap<>();

FileSystemResource resource= new FileSystemResource(newFile(filePath));

param.add("file", resource);

HttpHeaders headers= newHttpHeaders();

headers.setContentType(MediaType.MULTIPART_FORM_DATA);

HttpEntity> requestEntity = new HttpEntity<>(param, headers);

RestTemplate rest= newRestTemplate();

String restResult= rest.postForObject(url, requestEntity, String.class);

---------------------------------------------

发现一个问题,/download这个POST接口,@QueryParam这个注解虽然是post请求但是不会以body里的内容传参,而是用parameter传参,也就是get请求的传参方式

使用RestTemplate.postForObject无法调用,报错:Only resource methods using @FormParam will work as expected

@POST

@Path("/download")

@Produces(MediaType.APPLICATION_OCTET_STREAM)public Response download(@QueryParam("attachmentId") String attachmentId, @Context HttpServletResponse response) {

}

所以我改用httpclient,调用POST成功

/***@paramurl

* 下载路径

*@paramdownloadDir

* 下载存放目录*/

public static voiddownloadFile(String url, String downloadDir) {

File file= newFile(downloadDir);if (!file.exists()) { //如果文件不存在则下载

CloseableHttpClient httpclient =HttpClients.createDefault();try{

HttpPost httpPost= newHttpPost(url);

httpPost.addHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

CloseableHttpResponse response=httpclient.execute(httpPost);try{if (HttpStatus.SC_OK ==response.getStatusLine().getStatusCode()) {

HttpEntity entity=response.getEntity();if (entity != null) {

InputStream in=entity.getContent();

OutputStream out= newFileOutputStream(file);int size = 0;int lent = 0;byte[] buf = new byte[1024];while ((size = in.read(buf)) != -1) {

lent+=size;

out.write(buf,0, size);

}

in.close();

out.close();

}

EntityUtils.consume(entity);

}else{

logger.error("文件下载失败" +url);

}

}finally{

response.close();

}

}catch(Exception e) {

e.printStackTrace();

}finally{try{

httpclient.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,根据前端代码,我可以看出你的前端使用了 MVC 架构,因此我会为你编写三层架构的 Java 后端代码。 首先,我们需要创建三个层次的包:controller、service 和 dao。其中,controller 层负责接收请求并处理参数,service 层负责处理业务逻辑,dao 层负责与数据库进行交互。 以下是示例代码: Controller 层: ```java package com.example.demo.controller; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/get") public String getUserInfo(String userId) { return userService.getUserInfo(userId); } } ``` Service 层: ```java package com.example.demo.service; import com.example.demo.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserDao userDao; public String getUserInfo(String userId) { return userDao.getUserInfo(userId); } } ``` Dao 层: ```java package com.example.demo.dao; import org.springframework.stereotype.Repository; @Repository public class UserDao { public String getUserInfo(String userId) { // 模拟从数据库中获取用户信息 return "User info for user " + userId; } } ``` 这是一个基本的三层架构示例,你可以根据自己的需要进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值