废话少说,直接上代码:
   /**
* 测试上传图片
*
*/
public static void testUploadImage(){
String url = "http://xxxtest/Api/testUploadModelBaking";
String fileName = "e:/username/textures/antimap_0017.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
String ret = formUpload(url, textMap, fileMap,contentType);
System.out.println(ret);
//{"status":"0","message":"add succeed","baking_url":"group1\/M00\/00\/A8\/CgACJ1Zo-LuAN207AAQA3nlGY5k151.png"}
} /**
* 上传图片
* @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);
}
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");
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;
}

本文代码学习自:https://blog.csdn.net/Icywind1/article/details/85628099 ,csdn的代码格式让人抓狂,特复制一份。

java发送post请求,使用multipart/form-data的方式传递参数,可实现服务器间文件上传功能(转)的更多相关文章

  1. 【转】HTTP请求中的form data和request payload的区别

    jQuery的ajax方法和post方法分别发送请求,在后台Servlet进行处理时结果是不一样的,比如用$.ajax方法发送请求时(data参数是一个JSON.stringify()处理后的字符串, ...

  2. [转]HTTP请求中的form data和request payload的区别

    本文转自:http://www.cnblogs.com/btgyoyo/p/6141480.html jQuery的ajax方法和post方法分别发送请求,在后台Servlet进行处理时结果是不一样的 ...

  3. [整理]Ajax Post请求下的Form Data和Request Payload

    Ajax Post请求下的Form Data和Request Payload 通常情况下,我们通过Post提交表单,以键值对的形式存储在请求体中.此时的reqeuest headers会有Conten ...

  4. HTTP请求中的form data和request payload的区别

    HTML <form> 标签的 enctype 属性 在下面的例子中,表单数据会在未编码的情况下进行发送: <form action="form_action.asp&qu ...

  5. HTTP 请求中的 Form Data 与 Request Payload 的区别

    HTTP 请求中的 Form Data 与 Request Payload 的区别 前端开发中经常会用到 AJAX 发送异步请求,对于 POST 类型的请求会附带请求数据.而常用的两种传参方式为:Fo ...

  6. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  7. 通过java发送http请求

    通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...

  8. Java发送HTTPS请求

    前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...

  9. 使用Java发送Http请求的内容

    公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容.这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过. 学习了J ...

随机推荐

  1. html 出现粒子线条,鼠标移动会以鼠标为中心吸附的特效之canvas-nest.js插件

    我在网上看到一个很炫酷,很有趣的特效,网页上会有很多移动的粒子和线条,鼠标经过时会以鼠标为中心吸附过来,如果时间够久,会形成一个类似震动的.带辐条的车轮子的东西. 网上搜了一下,源码是github里面 ...

  2. Linux基础入门-目录结构及文件基本操作

    一.Linux的目录结构: Windows是以存储介质为主的,主要以盘符及分区来实现文件的管理,然后之下才是目录.但Linux的磁盘从逻辑上来说是挂载在目录上的,每个目录不仅能使用本地磁盘分区的文件系 ...

  3. tensorflow报cudnn错误

    E tensorflow/stream_executor/cuda/cuda_dnn.cc:363] Loaded runtime CuDNN library: 7.0.5 but source wa ...

  4. Windows硬链接 软链接 符号链接 快捷方式

    http://blog.nsfocus.net/shortcuthard-linkjunction-pointsymbolic-link/ Windows支持4种”链接”机制,分别是shortcut. ...

  5. Windows7环境下Excel2010中图片超链接默认打开程序修改

    在Windows7的环境下,打开Excel2010超链接图片,都是默认用IE打开.搜索了所有的中文网络,没有找到解决方案,且发现受此困扰的人不少.后来用纯英文搜索,终于找到解决方案并尝试成功. 1,操 ...

  6. 0002-小牛学堂大数据24期视频-架构Hadoop-Spark

  7. pc端布局的一点思考

    编写pc端页面需要注意些什么? 1.自适应最小屏幕,在小屏幕上样式不能错乱. 在桌面屏幕各分辨率使用比例中可以看到各桌面分辨率的使用比例,日常pc端开发我们会考虑到适配1024宽度大小的屏幕. 对于管 ...

  8. laravel-admin挖坑之旅

    1.git-bash下使用命令php artisan admin:make UserController --model=App\User会报错Model does not exists 要加多一个“ ...

  9. 解决WCF“接收对 http://xxx.svc 的 HTTP 响应时发生错误。这可能是由于服务终结点绑定未使用 HTTP 协议造成的。这还可能是由于服务器中止了 HTTP 请求上下文(可能由于服务关闭)所致"

    最近在工作中新加了一个接口,本地调试的时候,直接抛出“接收对 http://xxx.svc 的 HTTP 响应时发生错误.这可能是由于服务终结点绑定未使用 HTTP 协议造成的.这还可能是由于服务器中 ...

  10. Python读取文件内容与存储

    Python读取与存储文件内容 一..csv文件 读取: import pandas as pd souce_data = pd.read_csv(File_Path) 其中File_path是文件的 ...