java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例
java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例
HttpClient 测试类,提供get post方法实例
1 package com.zdz.httpclient; 2 3 import java.io.BufferedReader; 4 import java.io.DataInputStream; 5 import java.io.DataOutputStream; 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.InputStreamReader; 9 import java.io.OutputStream; 10 import java.net.HttpURLConnection; 11 import java.net.URL; 12 import java.util.HashMap; 13 import java.util.Iterator; 14 import java.util.Map; 15 import javax.activation.MimetypesFileTypeMap; 16 17 /** 18 * java通过模拟post方式提交表单实现图片上传功能实例 19 * 其他文件类型可以传入 contentType 实现 20 * @author zdz8207 21 * {@link http://www.cnblogs.com/zdz8207/} 22 * @version 1.0 23 */ 24 public class HttpUploadFile { 25 26 public static void main(String[] args) { 27 testUploadImage(); 28 } 29 30 /** 31 * 测试上传png图片 32 * 33 */ 34 public static void testUploadImage(){ 35 String url = "http://xxx/wnwapi/index.php/Api/Index/testUploadModelBaking"; 36 String fileName = "e:/chenjichao/textures/antimap_0017.png"; 37 Map<String, String> textMap = new HashMap<String, String>(); 38 //可以设置多个input的name,value 39 textMap.put("name", "testname"); 40 textMap.put("type", "2"); 41 //设置file的name,路径 42 Map<String, String> fileMap = new HashMap<String, String>(); 43 fileMap.put("upfile", fileName); 44 String contentType = "";//image/png 45 String ret = formUpload(url, textMap, fileMap,contentType); 46 System.out.println(ret); 47 //{"status":"0","message":"add succeed","baking_url":"group1\/M00\/00\/A8\/CgACJ1Zo-LuAN207AAQA3nlGY5k151.png"} 48 } 49 50 /** 51 * 上传图片 52 * @param urlStr 53 * @param textMap 54 * @param fileMap 55 * @param contentType 没有传入文件类型默认采用application/octet-stream 56 * contentType非空采用filename匹配默认的图片类型 57 * @return 返回response数据 58 */ 59 @SuppressWarnings("rawtypes") 60 public static String formUpload(String urlStr, Map<String, String> textMap, 61 Map<String, String> fileMap,String contentType) { 62 String res = ""; 63 HttpURLConnection conn = null; 64 // boundary就是request头和上传文件内容的分隔符 65 String BOUNDARY = "---------------------------123821742118716"; 66 try { 67 URL url = new URL(urlStr); 68 conn = (HttpURLConnection) url.openConnection(); 69 conn.setConnectTimeout(5000); 70 conn.setReadTimeout(30000); 71 conn.setDoOutput(true); 72 conn.setDoInput(true); 73 conn.setUseCaches(false); 74 conn.setRequestMethod("POST"); 75 conn.setRequestProperty("Connection", "Keep-Alive"); 76 conn.setRequestProperty("User-Agent", 77 "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); 78 conn.setRequestProperty("Content-Type", 79 "multipart/form-data; boundary=" + BOUNDARY); 80 OutputStream out = new DataOutputStream(conn.getOutputStream()); 81 // text 82 if (textMap != null) { 83 StringBuffer strBuf = new StringBuffer(); 84 Iterator iter = textMap.entrySet().iterator(); 85 while (iter.hasNext()) { 86 Map.Entry entry = (Map.Entry) iter.next(); 87 String inputName = (String) entry.getKey(); 88 String inputValue = (String) entry.getValue(); 89 if (inputValue == null) { 90 continue; 91 } 92 strBuf.append("\r\n").append("--").append(BOUNDARY) 93 .append("\r\n"); 94 strBuf.append("Content-Disposition: form-data; name=\"" 95 + inputName + "\"\r\n\r\n"); 96 strBuf.append(inputValue); 97 } 98 out.write(strBuf.toString().getBytes()); 99 } 100 // file 101 if (fileMap != null) { 102 Iterator iter = fileMap.entrySet().iterator(); 103 while (iter.hasNext()) { 104 Map.Entry entry = (Map.Entry) iter.next(); 105 String inputName = (String) entry.getKey(); 106 String inputValue = (String) entry.getValue(); 107 if (inputValue == null) { 108 continue; 109 } 110 File file = new File(inputValue); 111 String filename = file.getName(); 112 113 //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream 114 contentType = new MimetypesFileTypeMap().getContentType(file); 115 //contentType非空采用filename匹配默认的图片类型 116 if(!"".equals(contentType)){ 117 if (filename.endsWith(".png")) { 118 contentType = "image/png"; 119 }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) { 120 contentType = "image/jpeg"; 121 }else if (filename.endsWith(".gif")) { 122 contentType = "image/gif"; 123 }else if (filename.endsWith(".ico")) { 124 contentType = "image/image/x-icon"; 125 } 126 } 127 if (contentType == null || "".equals(contentType)) { 128 contentType = "application/octet-stream"; 129 } 130 StringBuffer strBuf = new StringBuffer(); 131 strBuf.append("\r\n").append("--").append(BOUNDARY) 132 .append("\r\n"); 133 strBuf.append("Content-Disposition: form-data; name=\"" 134 + inputName + "\"; filename=\"" + filename 135 + "\"\r\n"); 136 strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); 137 out.write(strBuf.toString().getBytes()); 138 DataInputStream in = new DataInputStream( 139 new FileInputStream(file)); 140 int bytes = 0; 141 byte[] bufferOut = new byte[1024]; 142 while ((bytes = in.read(bufferOut)) != -1) { 143 out.write(bufferOut, 0, bytes); 144 } 145 in.close(); 146 } 147 } 148 byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 149 out.write(endData); 150 out.flush(); 151 out.close(); 152 // 读取返回数据 153 StringBuffer strBuf = new StringBuffer(); 154 BufferedReader reader = new BufferedReader(new InputStreamReader( 155 conn.getInputStream())); 156 String line = null; 157 while ((line = reader.readLine()) != null) { 158 strBuf.append(line).append("\n"); 159 } 160 res = strBuf.toString(); 161 reader.close(); 162 reader = null; 163 } catch (Exception e) { 164 System.out.println("发送POST请求出错。" + urlStr); 165 e.printStackTrace(); 166 } finally { 167 if (conn != null) { 168 conn.disconnect(); 169 conn = null; 170 } 171 } 172 return res; 173 } 174 }
HttpClientTest.java
package com.zdz.httpclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; /** * HttpClient 测试类,提供get post方法实例 * @author zdz8207 * */ public class HttpClientTest { private static final String URL = "http://www.163.com"; private static final int PORT = 80; public static void main(String[] args) throws Exception { //测试get方法 doGetMethod(URL,PORT); //测试post方法 String posturl = "http://mail.163.com/"; doPostMethod(posturl,PORT); } /** * http get 方法 * @param url * @param port * @throws HttpException * @throws IOException * @return bodystring */ public static String doGetMethod(String url,int port) throws HttpException, IOException { HttpClient client = new HttpClient(); // 设置代理服务器地址和端口 client.getHostConfiguration().setHost(url, port); // 使用 GET 方法 GetMethod method = new GetMethod(url); //执行请求 client.executeMethod(method); // 打印服务器返回的状态 System.out.println(method.getStatusLine()); // 打印返回的信息 // System.out.println(method.getResponseBodyAsString()); // response body of large or unknown size. Using getResponseBodyAsStream instead is recommended. InputStream bodystreams = method.getResponseBodyAsStream(); String body = convertStreamToString(bodystreams); System.out.println(body); // 释放连接 method.releaseConnection(); return body; } /** * http post 方法 * @param url * @param port * @throws HttpException * @throws IOException * @return bodystring */ public static String doPostMethod(String url,int port) throws HttpException, IOException { HttpClient client = new HttpClient(); // 设置代理服务器地址和端口 client.getHostConfiguration().setHost(url, port); // 使用POST方法 PostMethod method = new PostMethod(url); //设置传递参数 NameValuePair agent = new NameValuePair("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows 2000)"); NameValuePair username = new NameValuePair("email", "xxx@163.com"); NameValuePair password = new NameValuePair("password", "xxxxxx"); method.setRequestBody(new NameValuePair[] { agent, username, password }); //执行请求 client.executeMethod(method); // 设置cookies // Cookie[] cookies = client.getState().getCookies(); // client.getState().addCookies(cookies); // 打印服务器返回的状态 System.out.println(method.getStatusLine()); // 打印返回的信息 // System.out.println(method.getResponseBodyAsString()); // response body of large or unknown size. Using getResponseBodyAsStream instead is recommended. InputStream bodystreams = method.getResponseBodyAsStream(); String body = convertStreamToString(bodystreams); System.out.println(body); // 释放连接 method.releaseConnection(); return body; } /** * 把InputStream 转换成String返回 * @param is InputStream * @return String * @throws UnsupportedEncodingException */ public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is));//输出的中文乱码 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf8")); //GBK StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
项目实例下载地址(包括对应jar包)
ps:New text file line delimiter选择不同导致控制台输出编码不同,如下图所示:
大自然,飘然的风,QQ群: python技术交流群:453879716,人工智能深度学习群:251088643
golang技术交流群:316397059,vuejs技术交流群:458915921 囤币一族:621258209,有兴趣的可以加入
微信公众号: 心禅道(xinchandao)投资论道
golang技术交流群:316397059,vuejs技术交流群:458915921 囤币一族:621258209,有兴趣的可以加入
微信公众号: 心禅道(xinchandao)投资论道