记录java接口开发

**最近项目需要写web接口对外客户端提供服务,百度了很多发现没有比较实用的,自己摸索了半天终于写出来了,不容易,自己做了一个记录,大神勿喷。
我自己理解的接口就是客户端通过访问服务器获取数据。
我这里是用http协议实现的接口,实现了很多,如用户查询,插入,头像上传等等,在这就说下头像上传吧。
先上代码
package
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class BaseServlet extends HttpServlet {
    private static final long serialVersionUID = 7900894904189731562L;
    //这个类主要是实现HttpServlet,做一个统一父类,以便于其他类继承  
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    // 统一做一些事情
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long starttime = System.currentTimeMillis();
        req.setCharacterEncoding("UTF-8");
        post(req, resp);
    }
    // 实现post的方法
    protected abstract void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
}
//package 这里是包位置  是自己的项目而定
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import net.sf.json.JSONObject;
public class FileUploadAction extends BaseServlet {
    private static final long serialVersionUID = -168772768724854574L;
    Logger logger = Logger.getLogger(FileUploadAction.class);
    //实现父类的post方法,
    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) {
        String result = null;
        PrintWriter out = null;
        Map<String, Object> map = new HashMap<String, Object>();
         //得到上传文件的保存目录,用来存放上传的图片
        String savePath = req.getServletContext().getRealPath("/commonfile");
        //获取文件的后缀名
        String ext = req.getParameter("ext");
        if (ext != null) {
            String fileExtName = ext.substring(ext.lastIndexOf(".") + 1);
            String saveFilename = makeFileName(fileExtName);
            result = writeTo(req, saveFilename, makePath(savePath), savePath);
            if (result != null) {
                map.put("信息:", "上传成功");
            } else {
                map.put("error","未检测到数据");
            }
        } else {
            map.put("error","传入文件为空");
        }
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        try {
            out = resp.getWriter();
            out.write(JSONObject.fromObject(map).toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.info(e + "连接异常");
        } finally {
            out.flush();
            out.close();
        }
    }
    public String writeTo(HttpServletRequest req, String saveFilename, String Path, String savePath) {
        ServletInputStream is = null;
        FileOutputStream out = null;
        try {
            is = req.getInputStream();
            out = new FileOutputStream(savePath + "/" + Path + "/" + saveFilename);
            byte buffer[] = new byte[1024];
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                out.write(buffer, 0, length);
            }
            is.close();
            out.close();
            return "commonfile/" + Path + "/" + saveFilename;
        } catch (IOException e) {
            logger.info(e + "写入异常");
        } finally {
            try {
                is.close();
                out.close();
            } catch (IOException e) {
                logger.info(e + "流关闭异常");
            }
        }
        return null;
    }
    private String makeFileName(String filename) {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String time = format.format(date);
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        filename = time + "_" + result + "." + filename;
        return filename;
    }
    private String makePath(String savePath) {
        String dir = null;
        File f1 = new File(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        File[] f2 = f1.listFiles();
        if (f2.length != 0) {
            String f3 = f2[f2.length - 1].getName();
            File f4 = new File(savePath + "/" + f3);
            File[] f5 = f4.listFiles();
            int a = f2.length;
            if (f5.length <= 10000) {
                dir = a + "";
            } else {
                dir = (a + 1) + "";
                File file = new File(savePath + "/" + dir);
                if (!file.exists()) {
                    file.mkdirs();
                }
            }
        } else {
            dir = 1 + "";
            File file = new File(savePath + "/" + dir);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        return dir;
    }
}
代码写完之后则要在web.xml中配这个接口
web.xml文件如下:
//<!DOCTYPE web-app PUBLIC
//"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
// "http://java.sun.com/dtd/web-app_2_3.dtd" >
//<web-app>
//	<display-name>Test</display-name>
//	<servlet>
//		<servlet-name>fileupload</servlet-name>
//		<servlet-class>test.FileUploadAction</servlet-class>
//	</servlet>
//	<servlet-mapping>
//		<servlet-name>fileupload</servlet-name>
//		<url-pattern>/file/upload</url-pattern>
//	</servlet-mapping>
//</web-app>
不知道为啥不能全部显示,粘贴去掉注释就好
配完之后写个测试类试试
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MyTest {
	public static void main(String[] args) {
		String str = "http://localhost:8080/test/file/upload?ext=jpg";
		String fileName = "D:\\1.jpg";
		try {
			URL url = new URL(str);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("content-type", "text/html");
			BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
			// 读取文件上传到服务器
			File file = new File(fileName);
			FileInputStream fileInputStream = new FileInputStream(file);
			byte[] bytes = new byte[1024];
			int numReadByte = 0;
			while ((numReadByte = fileInputStream.read(bytes, 0, 1024)) > 0) {
				out.write(bytes, 0, numReadByte);
			}
			out.flush();
			fileInputStream.close();
			// 读取URLConnection的响应
			DataInputStream in = new DataInputStream(connection.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
测试时先将FileUpload运行在server上,然后执行mytest。**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值