当前位置: 首页 >服务端 > java httpClient发送post 表单

java httpClient发送post 表单

java httpClient发送post 表单

import com.xxl.job.core.log.XxlJobLogger;import org.apache.log4j.Logger;import javax.activation.MimetypesFileTypeMap;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.Iterator;import java.util.List;import java.util.Map;public class HttpClientUtil implements java.io.Serializable {private static final long serialVersionUID = 1L;private final static Logger log = Logger.getLogger(HttpClientUtil.class);//方法主体	public static String formUpload(String urlStr, Map<String, String> textMap,Map<String, String> fileMap, List<String> nameList,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());// textif (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());}// fileif (fileMap != null) {Iterator iter = fileMap.entrySet().iterator();for (int i = 0;iter.hasNext();i++) {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);byte[] b = urlTobyte(inputValue);File file = getFileByBytes(b,nameList.get(i));String filename = file.getName();System.out.println(filename);//没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-streamcontentType = 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(".doc") || filename.endsWith(".docx")) {contentType = "application/msword";}else if (filename.endsWith(".mp4")) {contentType = "video/mpeg4";}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;}}retu res;}/**- * byte[]转File方法一 * @param bytes * @param fileName * @retu */public static File getFileByBytes(byte[] bytes,String fileName) {File file = new File("Tempalte",fileName);try {FileUtils.writeByteArrayToFile(file, bytes);} catch (Exception e) {e.printStackTrace();}retu file;}public static byte[] urlTobyte(String url) throws MalformedURLException {URL ur = new URL(url);BufferedInputStream in = null;ByteArrayOutputStream out = null;try {in = new BufferedInputStream(ur.openStream());out = new ByteArrayOutputStream(1024);byte[] temp = new byte[1024];int size = 0;while ((size = in.read(temp)) != -1) {out.write(temp, 0, size);}} catch (Exception e) {e.printStackTrace();} finally {try {in.close();} catch (IOException e) {e.printStackTrace();}}byte[] content = out.toByteArray();retu content;}}

作者:zzzzzheike
来源链接:https://blog.csdn.net/zzzzzheike/article/details/108572451

版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaclub.cn/server/112778.html

标签:HttpClient
分享给朋友:

“java httpClient发送post 表单” 的相关文章