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=90
try {
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();// 敏感api
conn.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;
}
}