Java调用Http接口(1)--编写服务端

2019-11-22 16:01:59来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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类

package com.inspur.common.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author wuyy
 *
 * @param <T>
 */
public class CallResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    
    /**
     * 返回码
     * 0 正常,其他异常
     */
    private int returnCode = 0;
    
    /**
     * 描述
     */
    private String description = "OK";
    
    /**
     * 结果数据
     */
    private T result;
    
    public CallResult(){}
    
    public CallResult(int returnCode, String description) {
        this.returnCode = returnCode;
        this.description = description;
    }
    
    public CallResult(int returnCode, String description, T result) {
        this.returnCode = returnCode;
        this.description = description;
        this.result = result;
    }
    
    public int getReturnCode() {
        return returnCode;
    }
    public void setReturnCode(int returnCode) {
        this.returnCode = returnCode;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public T getResult() {
        return result;
    }
    public void setResult(T result) {
        this.result = result;
    }
    

    @Override
    public String toString() {
        //return JSON.toJSONString(this, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty);
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }
    
}
View Code

2.2、User类

package com.inspur.demo.entity;

public class User {
    private String userId;
    private String userName;
    
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    @Override
    public String toString() {
        return "User [userId=" + userId + ", userName=" + userName + "]";
    }
}
View Code

2.2、FileUtil类

package com.inspur.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * 文件操作工具
 * 
 */
public class FileUtil {
    private FileUtil() {}
    
    public static void close(InputStream in) {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void close(OutputStream out) {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
View Code

3、部署

访问地址为:

http://localhost:8080/webframe/demo/test/getUser

http://localhost:8080/webframe/demo/test/addUser

http://localhost:8080/webframe/demo/test/multi


原文链接:https://www.cnblogs.com/wuyongyin/p/11913419.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【并发编程】Java中的原子操作

下一篇:Java的String类详解