Java调用Http接口(1)--编写服务端,
分享于 点击 7724 次 点评:62
Java调用Http接口(1)--编写服务端,
Http接口输入的数据一般是键值对或json数据,返回的一般是json数据。本系列文章主要介绍Java调用Http接口的各种方法,本文主要介绍服务端的编写,方便后续文章里的客户端的调用。文中所使用到的软件版本:Java 1.8.0_191、Spring 5.1.9。
1、服务端Controller
package com.inspur.demo.web.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; 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.multipart.MultipartFile; import com.inspur.common.entity.CallResult; import com.inspur.common.util.FileUtil; import com.inspur.demo.entity.User; @Controller @RequestMapping(value="/demo/test/", method = {RequestMethod.GET, RequestMethod.POST}) public class TestController { private static Logger logger = LoggerFactory.getLogger(TestController.class); @RequestMapping("getUser") @ResponseBody public CallResult<User> getUser(String userId, String userName) { User user = new User(); user.setUserId(userId); user.setUserName(userName); CallResult<User> result = new CallResult<User>(0, "OK", user); return result; } /** * 传入json * @param user * @return */ @RequestMapping("addUser") @ResponseBody public CallResult<String> addUser(@RequestBody User user) { logger.info(user.toString()); CallResult<String> result = new CallResult<String>(0, "OK", "用户增加成功"); return result; } /** * 上传文件和参数 * @param file * @param type * @return */ @RequestMapping("multi") @ResponseBody public CallResult<String> multi(@RequestParam("file") MultipartFile file, String param1, String param2) { logger.info("file={},param1={},param2={}", file.getOriginalFilename(), param1, param2); InputStream in = null; OutputStream out = null; CallResult<String> result = new CallResult<String>(0, "OK", "上传成功"); try { in = new BufferedInputStream(file.getInputStream(), 16 * 1024); String fileName = "d:/temp/multi_" + System.currentTimeMillis() + "_" + file.getOriginalFilename(); out = new BufferedOutputStream(new FileOutputStream(fileName), 16 * 1024); byte[] buffer = new byte[16 * 1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } catch (Exception e) { result = new CallResult<String>(-1, "发生异常", ""); e.printStackTrace(); } finally { FileUtil.close(in); FileUtil.close(out); } return result; } }
2、其他辅助类
2.1、CallResult类

2.2、User类

2.2、FileUtil类

3、部署
访问地址为:
http://localhost:8080/webframe/demo/test/getUser
http://localhost:8080/webframe/demo/test/addUser
http://localhost:8080/webframe/demo/test/multi
相关文章
- 暂无相关文章
用户点评