通过java调用Http接口上传图片到服务器
https://blog.csdn.net/jaedons/article/details/78563841
/**
* 测试上传png图片
*
*/
public static void testUploadImage(){
String url = "http://localhost:8080/app/remindDetails/doRepair.xhtml";
String fileName = "E:\\工作\\项目\\奇瑞只能制造信息化系统\\工作安排\\接口设计(20171113-)\\1.5.png";
Map<String, String> textMap = new HashMap<String, String>();
//普通参数:可以设置多个input的name,value
textMap.put("name", "testname");
textMap.put("type", "2");
//文件:设置file的name,路径
Map<String, String> fileMap = new HashMap<String, String>();
fileMap.put("upfile", fileName);
String contentType = "";//image/png
formUpload(url, textMap, fileMap,contentType);
} /**
* 上传图片
* @param urlStr
* @param textMap
* @param fileMap
* @param contentType 没有传入文件类型默认采用application/octet-stream
* contentType非空采用filename匹配默认的图片类型
* @return 返回response数据
*/
@SuppressWarnings("rawtypes")
public static String formUpload(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap,String contentType) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "---------------------------123821742118716";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
System.out.println(inputName+","+inputValue);
}
out.write(strBuf.toString().getBytes());
}
// file
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
File file = new File(inputValue);
String filename = file.getName(); //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
contentType = new MimetypesFileTypeMap().getContentType(file);
//contentType非空采用filename匹配默认的图片类型
if(!"".equals(contentType)){
if (filename.endsWith(".png")) {
contentType = "image/png";
}else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
contentType = "image/jpeg";
}else if (filename.endsWith(".gif")) {
contentType = "image/gif";
}else if (filename.endsWith(".ico")) {
contentType = "image/image/x-icon";
}
}
if (contentType == null || "".equals(contentType)) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"; filename=\"" + filename
+ "\"\r\n");
System.out.println(inputName+","+filename); strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(
new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
通过java调用Http接口上传图片到服务器的更多相关文章
- Java 调用http接口(基于OkHttp的Http工具类方法示例)
目录 Java 调用http接口(基于OkHttp的Http工具类方法示例) OkHttp3 MAVEN依赖 Http get操作示例 Http Post操作示例 Http 超时控制 工具类示例 Ja ...
- Java调用webservice接口方法
java调用webservice接口 webservice的 发布一般都是使用WSDL(web service descriptive langu ...
- (二)通过JAVA调用SAP接口 (增加一二级参数)
(二)通过JAVA调用SAP接口 (增加一二级参数) 一.建立sap连接 请参考我的上一篇博客 JAVA连接SAP 二.测试项目环境准备 在上一篇操作下已经建好的环境后,在上面的基础上新增类即可 三. ...
- Java调用RestFul接口
使用Java调用RestFul接口,以POST请求为例,以下提供几种方法: 一.通过HttpURLConnection调用 1 public String postRequest(String url ...
- Java调用第三方接口工具类(json、form)
1.JSON值访问 /** * 调用对方接口方法 * @param path 对方或第三方提供的路径 * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析 ...
- java 调用webservice接口wsdl,推荐使用wsdl2java,放弃wsimport
网上说wsimport是jdk1.6后自带的客户端生成调用webservice接口的工具,其实我挺喜欢原生的东西,毕竟自家的东西用着应该最顺手啊,但往往让人惊艳的是那些集成工具. 本机jdk1.8.1 ...
- Java调用第三方接口示范
在项目开发中经常会遇到调用第三方接口的情况,比如说调用第三方的天气预报接口. 使用流程[1]准备工作:在项目的工具包下导入HttpClientUtil这个工具类,或者也可以使用Spring框架的res ...
- 三种方法实现java调用Restful接口
1,基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...
- Java 调用 php接口(Ajax)(二)
由于项目里面需要用到Java调用PHP的充值接口,所以学习了一下,以下这个Demo是个小小的例子,写下来做个笔记> jsp页面: <%@ page language="java& ...
随机推荐
- Gym - 100676F Palindrome —— 并查集
题目链接:https://vjudge.net/contest/155789#problem/E 题解: 由于是回文串,所以可以先将在对称位置的字符放在同一个集合(如果期间有两个非‘?’,且不相等,则 ...
- x264 --fullhelp
>x264 --fullhelp x264 core: Syntax: x264 [options] -o outfile infile Infile can be raw (in which ...
- cygwin Could not create directory '/home/Administrator/.ssh'
在cygwin下运行: ssh-keygen -C "634772208@qq.com" -t rsa 时,出现如下错误: cygwin Could not create dire ...
- [ZJU 2112] Dynamic Rankings
[题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1901 [算法] 首先 , 考虑没有修改操作 不妨建立可持久化线段树 , 第i棵树维护 ...
- css td 溢出改为省略号
<style> .table{ table-layout: fixed; width:100%; } .td{ width:100px; white-space: nowrap; over ...
- linux 查看某进程 并杀死进程 ps grep kill
Linux 中使用top 或 ps 查看进程使用kill杀死进程 1.使用top查看进程: $top 进行执行如上命令即可查看top!但是难点在如何以进程的cpu占用量进行排序呢? cpu占用量排序执 ...
- cobbler api
try: import xmlrpclib except ImportError as e: import xmlrpc.client SERVER_IP = '192.168.144.11' try ...
- atom 的一些东东
一. 配置atom atom 有些插件被墙了, 往往导致无法下载插件, 网上查了一些解决方案, 大部分就两种解决方案. 配置国内源 离线下载插件 1. 配置国内源 Linux 在 /home/user ...
- CSS元素:clip属性作用说明
clip属性是一个比较有用的属性,但往往在实际应用中,并不多见,介绍的也很少.应用clip属性需要注意的两点: 一.clip属性必须和定位属性postion一起使用才能生效. 二.clip裁切的计算坐 ...
- 通过url在两个页面之间传值
今天开发遇到一个需要通过url传值才能解决的问题,就查了一下资料 一下是整理的结果: 假如需要把a页面的值传到b页面 a页面代码 <script type="text/javascri ...