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 ...
随机推荐
- linux centos ftp服务器搭建
原文参考 步骤一:构建vsftpd服务器 1)使用yum安装vsftpd软件包yum -y install vsftpdrpm -q vsftpd #确认安装成功,显示vsftpd对应版本 vsftp ...
- go html 转字符串存mysql表中
func HTMLMarshal(str string) (returnStr string) { bf := bytes.NewBuffer([]byte{}) jsonEncoder := jso ...
- 工作 巧遇 sql 查询 一组数据中 最新的一条
SELECT * FROM rsl a, (SELECT CODE, max(time_key) time_key FROM rsl GROUP BY CODE ) b WHERE a. CODE = ...
- Windows服务启动时候报错1053
用.net 开发了一个C#语言的windows服务,在本地和测试环境,安装启动都正常,在新的线上环境报错,不能启动-报出-错误1053:服务没有及时响应启动或控制请求. 后来发现时线上.NET FRA ...
- CF1156E Special Segments of Permutation
思路:笛卡尔树?(好像并不一定要建出来,但是可以更好理解) 提交:2次 错因:没有判左右儿子是否为空来回溯导致它T了 题解: 建出笛卡尔树,考虑如何计算答案: 先预处理每一个值出现的位置 \(pos[ ...
- 007_linuxC++之_构造函数的初级应用
(一)构造函数:用来在创建对象时初始化对象, 即为对象成员变量赋初始值 (二)构造函数的命名必须和类名完全相同 (三)更对具体的查看:构造函数 (四)直接分析程序 运行结果 解析上面程序: 1. 当程 ...
- Linq to AD
輕鬆找出域中所有用戶,組,而且還可以更改 LINQ to Active Directory https://linqtoad.codeplex.com/ LINQ to LDAP http://lin ...
- Codeforces 1220 E Tourism
题面 可以发现一个边双必然是可以随意走的,所以我们就把原图求割边然后把边双缩成一个点,然后就是一个树上dp了. #include<bits/stdc++.h> #define ll lon ...
- Codevs 1743 反转卡片(splay)
1743 反转卡片 时间限制: 2 s 空间限制: 256000 KB 题目等级 : 大师 Master 题目描述 Description [dzy493941464|yywyzdzr原创] 小A将N ...
- 【线性代数】6-3:微分方程的应用(Applications to Differential Equations)
title: [线性代数]6-3:微分方程的应用(Applications to Differential Equations) categories: Mathematic Linear Algeb ...