package com.jiepu.lucene5_2;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import javax.net.ssl.HttpsURLConnection;import net.sf.jmimemagic.Magic;import net.sf.jmimemagic.MagicException;import net.sf.jmimemagic.MagicMatch;import net.sf.jmimemagic.MagicMatchNotFoundException;import net.sf.jmimemagic.MagicParseException;public class HttpPostUploadUtil {private static String urlStr = "http://127.0.0.1:9090/xxxx/index.html";/** * @param args * @throws MagicException  * @throws MagicMatchNotFoundException  * @throws MagicParseException  */public static void main(String[] args) throws Exception {if(false){String filepath = "d:\\test.jpg";MagicMatch match = Magic.getMagicMatch(new File(filepath), true, false);String contentType = match.getMimeType();System.out.println(contentType);return ;}//test001();test002();}private static void test002() {Map params = new HashMap();params.put("module", "upload");params.put("action", "uploadPhoto");System.out.println(sendPOSTRequest(urlStr,params,"utf-8"));}private static void test001() {String filepath = "d:\\test.jpg";Map params = new HashMap();params.put("module", "upload");params.put("action", "uploadPhoto");Map fileMap = new HashMap();fileMap.put("file", filepath);fileMap.put("file1", "d:\\test.html");fileMap.put("file2", "d:\\test.png");String ret = formUpload(urlStr, params, null,"image/jpg");System.out.println(ret);}/** * 发送Post请求 * @param path 请求路径 * @param params 请求参数 * @param encoding 编码 * @return 请求是否成功 */public static boolean sendPOSTRequest(String path, Map params, String encoding) {//  title=liming&timelength=90try {StringBuilder data = new StringBuilder();if(params!=null && !params.isEmpty()){for(Map.Entry entry : params.entrySet()){data.append(entry.getKey()).append("=");data.append(URLEncoder.encode(entry.getValue(), encoding));data.append("&");}data.deleteCharAt(data.length() - 1);}byte[] entity = data.toString().getBytes();//生成实体数据URL url=new URL(path);// 下面开始测试HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("POST");conn.setDoOutput(true);//允许对外输出数据conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", String.valueOf(entity.length));OutputStream outStream = conn.getOutputStream();outStream.write(entity);//conn.connect();// 敏感apiconn.connect();if(conn.getResponseCode() == 200){return true;}else{return false;}} catch (Exception e) {e.printStackTrace();return false;} }/** * 上传图片 * @param urlStr * @param textMap * @param fileMap * @return */public static String formUpload(String urlStr, Map textMap, Map fileMap,String contentType) {String res = "";HttpURLConnection conn = null;String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符  try {URL url = new URL(urlStr);conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(10000);conn.setReadTimeout(10000);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 = 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());System.out.println(strBuf.toString());}// file  if (fileMap != null) {Iterator> iter = fileMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry 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();//MagicMatch match = Magic.getMagicMatch(file, false, true);//String contentType = match.getMimeType();//String 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;}}


 

更多相关文章

  1. Android摄像头视频帧数据测试代码
  2. Android(安卓)SmsManager(短信管理器),发送短信息
  3. Android短信发送器
  4. Android_在线视频播放器
  5. HttpURLConnection和HttpClient使用
  6. Android(安卓)通信录中的联系人操作
  7. android 如何在对话框中获取edittext中的数据
  8. facebook的Android调试工具Stetho介绍
  9. Android(安卓)IPC 通讯机制源码分析 二

随机推荐

  1. 分析PHP错误处理(核心特性)
  2. PHP操作Redis数据库常用方法(总结)
  3. PHP使用redis作为缓存(高效技术)
  4. php性能优化的方法介绍
  5. php实现顺序线性表
  6. Kubernetes 如果是个水族馆
  7. 自学系列 | 就谈自我管理!
  8. 智慧城市信息安全探讨
  9. 1-22
  10. 动画:面试必刷之二叉树的子结构