Rest Post示例(java服务端、python客户端)
前提:服务端是现成的,java、springMVC、resttemplate、jboss等;突然有个需要,要在windows上开发一个客户端,作用是定期向服务端上传文件。想了想,如果客户端写一个java程序,势必要求在windows上安装java的运行环境,这样比较麻烦。后来的解决思路是写python的程序,然后打包成exe在windows上执行。以下是Rest Post示例的服务端、客户端代码。
server端代码:
@RequestMapping(value = "/uploadScriptResult") public @ResponseBody OperateResult uploadScriptResult(MultipartFile files){ //public @ResponseBody OperateResult uploadScriptResult(@RequestParam(value="files",required=false) MultipartFile files){ OperateResult result = new OperateResult(); try { log.info("uploadScriptResult start. "); result = uploadFile(files); } catch (Exception e) { log.error("uploadScriptResult error", e); result.setStatus(false); result.setMsg(e.getMessage()); } return result; } private OperateResult uploadFile(MultipartFile file) { OperateResult result = new OperateResult(); log.info("upload file start"); String basePath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/") + Constants.REMOTE_SCRIPT_TEST_DIR + "execresult/" + getDate() + "/"; File uploadPath =new File(basePath); if(!uploadPath.exists()) { uploadPath.mkdir(); } String name = file.getOriginalFilename(); name = name + "." + System.currentTimeMillis() + ".execresult.txt"; String resourceURL = basePath + name; try { file.transferTo(new File(resourceURL)); log.info("transfer file To: " + resourceURL + "success!"); result.setMsg(name); } catch (Exception e1) { log.error("upload file error! resourceURL=" + resourceURL, e1); String msg = "upload file error resourceURL=" + resourceURL + " OriginalFilename: " + file.getOriginalFilename(); result.setStatus(false); result.setMsg(msg); } return result; } private String getDate(){ Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dateNowStr = sdf.format(d); return dateNowStr; } public class OperateResult { private Boolean status; private String msg; public OperateResult(){ this.status = true; this.msg = ""; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
client端代码:
import urllib import urllib2 import requests from poster.encode import multipart_encode from urllib2 import Request, urlopen, URLError, HTTPError from poster.encode import multipart_encode from poster.streaminghttp import register_openers def uploadFile(filePath, url): register_openers() datagen, headers = multipart_encode({"files": open(filePath, "rb")}) request = urllib2.Request(url, datagen, headers) response = urllib2.urlopen(request) print response.read() if __name__ == "__main__": uploadFile("/home/testResult", "http://192.168.7.144:8888/starott_cloud_client/remotescripttest/uploadScriptResult");