httpurlConnection客户端发送文件与服务端接受文件
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection; import org.apache.commons.lang.StringUtils;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration; import com.kexion.eagle.common.dao.DaoException;
import com.kexion.ssdr.dmp.web.utils.PropertiesUtil;
//客户端发送
public class TestSendFile { public static void main(String[] args) {
try {
sendFile1("Template_ZYMLBZHJC.xlsx", "D:"+File.separatorChar+"2019"+File.separatorChar+"个人"+File.separatorChar+"Template_ZYMLBZHJC.xlsx", "zxsb");
} catch (Exception e) {
e.printStackTrace();
}
}
private static String sendFile1(String filename,String dir,String type) throws Exception {
PropertiesUtil util = new PropertiesUtil("config/zymlk.properties");
Object obj = util.get(type);
if(obj==null){
throw new Exception("调用省厅接口失败");
}
String actionUrl = (java.lang.String) util.get(type);
if(StringUtils.isEmpty(actionUrl)){
throw new Exception("调用省厅接口失败");
} String u1 = actionUrl+"?filename="+filename;
URL url =new URL(u1);
System.out.println(u1);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-type", "text/html");
httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect(); OutputStream out = httpURLConnection.getOutputStream();
DataInputStream in = null; File file = new File(dir);
in = new DataInputStream(new FileInputStream(file));
int bytes=0;
byte[] buffer = new byte[1024];
while((bytes=in.read(buffer))!=-1){
out.write(buffer,0,bytes);
}
out.flush(); InputStream inputStream=null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = null;
if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_OK){
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
String tmpLine = null;
resultBuffer = new StringBuffer();
while((tmpLine=reader.readLine())!=null){
resultBuffer.append(tmpLine);
resultBuffer.append("\n");
}
}else{
int code=httpURLConnection.getResponseCode()
throw new DaoException("上报失败,失败代码["+code+"]");
} in.close();
out.close();
reader.close();
inputStreamReader.close();
inputStream.close();
System.out.println(resultBuffer.toString());
return resultBuffer.toString();
} }
//服务端接收
package com.dd.demo.controller; import java.io.*;
import java.util.List; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
public class StbmglController {
//打印日志
private static final Logger logger = LoggerFactory.getLogger(StbmglController.class); @ResponseBody
@RequestMapping("getDsFile1")
public String getDsFile1(HttpServletRequest request,HttpServletResponse response){
logger.info("开始接受文件");
JSONObject result = new JSONObject();
try { String filename = request.getParameter("filename");
logger.info("filename={}",filename);
InputStream input = request.getInputStream();
File getFile = new File("C:\\Users\\Administrator\\Desktop\\"+filename); FileOutputStream fos = new FileOutputStream(getFile);
boolean flag = false;
int size = 0;
byte[] buffer = new byte[1024];
while ((size=input.read(buffer,0,1024))!=-1){
flag = true;
fos.write(buffer,0,size);
}
result.put("success",flag);
} catch (Exception e) {
result.put("success",false);
result.put("msg","接受文件失败");
logger.error("接受文件失败");
e.printStackTrace();
}
return result.toString();
}
}
httpURLConnection.getResponseCode()
httpurlConnection客户端发送文件与服务端接受文件的更多相关文章
- android 上传文件用php程序在服务端接受(一)
php服务端接受程序..file_up.php. <?php /* require_once('lib/session_config.php'); require_once('lib/flydc ...
- Java后端HttpClient Post提交文件流 及服务端接收文件流
客户端将文件转换为流发送: 依赖的包: <dependency> <groupId>org.apache.httpcomponents</groupId> < ...
- android 发送GET请求 服务端接收乱码的问题
在android的编程中常会使用get/post请求,在用get请求的时候数据是直接放在url当中的 例如: http://apicloud.mob.com/v1/weather/query?key= ...
- C#中服务端接受前端JSON字符串转换成字典集合
我们是否可以把从前端接受的JSON字符串转换成字典集合呢? 比如从前端接收:{'size':'10', 'weight':'10kg'} 在服务端转换成:[{size:"10"}, ...
- PHP学习笔记——上传文件到服务端的文件夹下
环境 开发包:appserv-win32-2.5.10 服务器:Apache2.2 数据库:phpMyAdmin 语言:php5,java 平台:windows 10 需求 编写一个PHP脚本页面,可 ...
- Eureka客户端续约及服务端过期租约清理源码解析
在之前的文章:EurekaClient自动装配及启动流程解析中,我们提到了在构造DiscoveryClient时除了包含注册流程之外,还调度了一个心跳线程: scheduler.schedule( n ...
- SpringMVC文件上传下载(单文件、多文件)
前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...
- httpurlconnection发送文件到服务端并接收
httpurlconnection发送文件到服务端并接收 客户端 import java.io.DataInputStream; import java.io.File; import java.io ...
- PHP-Socket服务端客户端发送接收通信实例详解
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://fighter.blog.51cto.com/1318618/1533957 So ...
随机推荐
- python自动华 (四)
Python自动化 [第四篇]:Python基础-装饰器 生成器 迭代器 Json & pickle 目录: 装饰器 生成器 迭代器 Json & pickle 数据序列化 软件目录结 ...
- paramiko获取主机信息
import re import paramiko host="192.168.4.88" user = "root" password = " cl ...
- JSON格式数据
1. 基础知识 1. 什么是JSON格式? JSON格式是现在网站数据交互的标准数据格式,写入标准. 取代原来的XML:符合JS原生语法,可以被直接解析,不需要额外的解析文件. 书写简单,一目了然 2 ...
- sql server 复习笔记2
主键约束 可以通过定义primary key 约束来定义主键, 用于强制表的实体化完整性,一个表只能有一个主键约束, 并且primary key 约束中的列不能为空值,由于primary key 约束 ...
- 通过无线网络使用ADB ( Connect to android with ADB over TCP )
之前用USB数据线连接电脑和android手机,用adb操控手机. 后来电脑前面板的USB全坏了,键盘.鼠标.USBKkey.打印机都需USB, 少一个USB口,只得对不常用设备进行插拔切换. 于是 ...
- kill函数
kill函数/命令产生信号 kill命令产生信号:kill -SIGKILL pid kill函数:给指定进程发送指定信号(不一定杀死) int kill(pid_t pid, int sig); ...
- ansible的become
# ansible sudo 问题 官方下载centos7.6fcow2镜像不给直接远程ssh了,所以必须sudo,但是有的命令sudo也解决不了的如管道重定向还有多个命令组合. 解决办法: vim ...
- 在centos7上使用packstack安装openstack
简介 Packstack主要是由Redhat推出的用于概念验证(PoC)环境快速部署的工具.Packstack是一个命令行工具,它使用Python封装了Puppet模块,通过SSH在服务器上部署Ope ...
- 十二、 RAID
https://blog.51cto.com/sonlich http://note.youdao.com/noteshare?id=17083150f38dd19343f82ea6cc0e0e62& ...
- 本地项目文件通过git提交到GitHub上
参考:https://blog.csdn.net/kongying19910218/article/details/50515834 步骤: 1.初始化git,假如我们要提交test文件夹下的所有目录 ...