@RequestBody内容解释解析

1,数据发送json

 public  boolean SendProcessTowebSite(String totalSize, String proessSize, String taskId, String fileName, String type){
    	
    	Map<String,String> map=new HashMap<>();
    	map.put("fileName", fileName);
    	map.put("taskId", taskId);
    	map.put("proessSize", proessSize);
    	map.put("totalSize", totalSize);
    	map.put("type", type);
    	JSONObject json = JSONObject.fromObject(map);
    	
    	HttpClient httpclient = new DefaultHttpClient();
    	// 连接时间
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60 * 1000);
        // 数据传输时间
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60 * 1000);
    	
    	HttpPost httppost = new HttpPost("http://100.120.6.245:20185/xdevicesite/logprocess/insert/");
    	
    	try {
			StringEntity s = new StringEntity(json.toString(),"utf-8");
			logger.info("send pyweb message>>>>"+json.toString());
			s.setContentEncoding("UTF-8");
			
			s.setContentType("application/json");
			
			httppost.setEntity(s);
			
			HttpResponse res = httpclient.execute(httppost);
			logger.info("StatusCode>>>>>>>"+res.getStatusLine().getStatusCode());
			if(res.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				HttpEntity entity=res.getEntity();
				String resault = EntityUtils.toString(entity);
				
				logger.info(String.format("response: [%s]", resault));
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    	logger.info("send fail");
    	return false;
    }

2,使用fastjson解析

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

 @RequestMapping("test")
	    @ResponseBody
	    public void testbody(HttpServletResponse reso,HttpServletRequest resq,@RequestBody JSONObject obj )throws IOException{
	    	log.info("data:"+obj.toJSONString());
	    	JSONObject json= JSON.parseObject(obj.toJSONString());
	    	String body=json.getString("body");
	    	
	    	String[] bodylist=body.split(",");
	    	for(int i=0;i<bodylist.length;i++){
	    		System.out.println(URLDecoder.decode(bodylist[i], "UTF-8"));
	    	}
	    	
	    	Map<String, String> map=new HashMap<>();
	    	
	    	map.put("resault", "sucess");
	    	PrintWriter out=reso.getWriter();
	        String s= JSON.toJSONString(map);
		       // System.out.println(s);
		        out.write(s);
		        out.flush();
		        out.close();
	    }

3,发送文件

 public boolean uploadFileToGDTC215(String req,String fileName,String filePath){
        Message reponse = null;
        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            // 连接时间
            httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60 * 1000);
            // 数据传输时间
            httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60 * 1000);
            HttpPost httppost = new HttpPost("http://" + preferences.getSgdtcIp() + ":" + preferences.getSgdtcPort() + preferences.getSgdtcUrl());
            logger.info("url:" + "http://" + preferences.getSgdtcIp() + ":" + preferences.getSgdtcPort() + preferences.getSgdtcUrl());

            httppost.addHeader("req", req);
            httppost.addHeader("fileName", URLEncoder.encode(fileName,"utf-8"));
            logger.info("req:[" + req + "]、" + "fileName:[" + fileName + "]、");
            byte[] fileBytes = MessageUtil.changeFileToByteArray(new File(filePath));

            httppost.setEntity(new ByteArrayEntity(fileBytes, ContentType.APPLICATION_OCTET_STREAM));

            HttpResponse response = httpclient.execute(httppost);
            // 解析返回消息
            HttpEntity rspEntity = response.getEntity();
            reponse = Message.getMessage(rspEntity);
            logger.info("215"+reponse);
        }
        catch (Exception e)
        {
//            e.printStackTrace();
            logger.error(e);
        }
        
        if (reponse == null || reponse.getJsonMsg() == null)
        {
            logger.error(String.format("Failed to upload file [%s],response is null!", filePath));
            return false;
        }
        org.json.simple.JSONObject json = reponse.getJsonMsg();
        JSONObject resultJson = (JSONObject) json.get("result");
        int status = Integer.parseInt((Long) resultJson.get("status") + "");
        if (status == 1)
        {
            // 1:失败 | 0:成功
            logger.error(String.format("Failed to upload file [%s],response status is 1!", filePath));
            return false;
        }
        logger.debug("uploadFile end......");
        return true;
    }
    /获取字节流
    public static byte[] changeFileToByteArray(File file) throws IOException
    {
        // 读取数据byte数组
        byte[] fileBytes = new byte[(int) file.length()];
        
        int offset = 0;
        int numRead = 0;
        InputStream is = null;
        /**
         * 当文件过大时可能会导致电脑死机......因为缓存读取中缓存过大
         */
        try
        {
            is = new FileInputStream(file);
            while (offset < fileBytes.length
                    && (numRead = is.read(fileBytes, offset, fileBytes.length
                            - offset)) >= 0)
            {
                offset += numRead;
            }
        }
        catch (Exception e)
        {
//            e.printStackTrace();
            logger.error(e);
        }
        finally
        {
        	IOUtils.closeQuietly(is);
        }
        
        // 确保所数据均读取
        if (offset < fileBytes.length)
        {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        return fileBytes;
    }

4,接收文件

 public String saveFile(HttpServletRequest request, String dirPath,
        String fileName)
    {
        
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try
        {
            
            // 创建文件夹
            mkdirs(dirPath);
            
            long startTime = System.currentTimeMillis();
            
            String filePath = dirPath + File.separator + fileName;
            bis = new BufferedInputStream(request.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(new File(
                    filePath)));
            
            int len = -1;
            byte[] buffer = new byte[ConsUtil.ONE_KB];
            while ((len = bis.read(buffer)) != -1)
            {
                bos.write(buffer, 0, len);
            }
            bos.flush();
            long endTime = System.currentTimeMillis();
            logger.info(String.format("Success to save the file[%s] to the path[%s], and spend [%s]ms.",
                    fileName,
                    dirPath,
                    endTime - startTime));
            return filePath;
            
        }
        catch (RuntimeException e)
        {
            logger.info(e);
        }
        catch (Exception e)
        {
            logger.info("save file failed with exception:" + e);
        }
        finally
        {
            Util.close(bos);
            Util.close(bis);
        }
        
        return null;
    }
    //获取文件名
     public String getHeaderParameter(HttpServletRequest request,
        String paramName)
    {
        String paramValue = StringUtils.EMPTY;
        Enumeration<String> params = request.getHeaders(paramName);
        if (Util.isNotNull(params))
        {
            while (params.hasMoreElements())
            {
                paramValue = params.nextElement();
            }
        }
        
        return StringUtils.isBlank(paramValue) ? StringUtils.EMPTY
                : paramValue.trim();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值