通过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& ...
随机推荐
- 把tomcat写到Windows系统服务器的服务中
首先准备一个免安装的tomcat服务器,和一个Windows系统. 在“C:\Windows\SysWOW64”中找到cmd.exe的执行文件,以管理员身份启动: 进入到tomcat的bin文件夹, ...
- Machine Learning in Action(1) K-近邻
机器学习分两大类,有监督学习(supervised learning)和无监督学习(unsupervised learning).有监督学习又可分两类:分类(classification.)和回归(r ...
- 微信 jssdk 逻辑在 vue 中的运用
微信 jssdk 在 vue 中的简单使用 import wx from 'weixin-js-sdk'; wx.config({ debug: true, appId: '', timestamp: ...
- nginx启动不了
nginx简介 Nginx是一个高性能的HTTP和反向代理服务器. 支持的操作系统众多,windows.linux. MacOS X: 可实现负载均衡: Rewrite功能强大: 电商架构大部分都采用 ...
- 加快你的JavaScript加载时间
发现可以提速的内容 你必须首先发现你的什么图片和HTML加载缓慢了你的脚本速度,下面提供了方法: 1. Firefox web-developer toolbar 2. Firebug Plugi ...
- (QA-LSTM)自然语言处理:智能问答 IBM 保险QA QA-LSTM 实现笔记.md
train集: 包含若干条与保险相关的问题,每一组问题对为一行,示意如下: 可分为四项,第三项为问题,第四项为答案: 1.build_vocab 统计训练集中出现的词,返回结果如下(一个包含3085个 ...
- AOP原理
AOP(面向切面编程):扩展功能时不修改源代码,采用横向抽取机制 纵向抽取机制: 横向抽取机制: 第一种情况: 第二种情况:
- call,apply,bind与es6的数组扩展运算符...
js中每一个Function对象都有一个apply个一个call方法: function.apply(thisObj,[argArray]); function.call(thisObj,arg1,a ...
- 启动Android模拟器问题集锦
1.新建AVD时,报错“no CPU/ABI system image available for this target”, 解决:在SDK Manager中下载System Image 2.Sys ...
- POJ - 2312 Battle City BFS+优先队列
Battle City Many of us had played the game "Battle city" in our childhood, and some people ...