httpconnent传输附件
发送方:
package com.zte.mdm.home.util;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* @see 通过HttpURLConnection请求商家系统进行商家注册
* @author zhengcf
* @since 2015/02/28
*/
public class HttpPostUtil {
URL url;
HttpURLConnection conn;
String boundary = "--------httppost";
Map<String, String> textParams = new HashMap<String, String>();
Map<String, File> fileparams = new HashMap<String, File>();
DataOutputStream ds;
String para;
public HttpPostUtil(String url) throws Exception {
this.url = new URL(url);
}
/**
* @author zcf
* @param url
* @throws Exception
*/
//重新设置要请求的服务器地址,即上传文件的地址。
public void setUrl(String url) throws Exception {
this.url = new URL(url);
}
//增加一个普通字符串数据到form表单数据中
public void addTextParameter(String name, String value) {
textParams.put(name, value);
}
//批量增加字符类键值对
public void addAllTextParameter(Map<String, String> Params) {
textParams.putAll(Params);
}
//增加一个文件到form表单数据中
public void addFileParameter(String name, File value) {
fileparams.put(name, value);
}
// 清空所有已添加的form表单数据
public void clearAllParameters() {
textParams.clear();
fileparams.clear();
}
// 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
public byte[] send() throws Exception {
initConnection();
try {
conn.connect();
} catch (SocketTimeoutException e) {
// something
throw new RuntimeException();
}
ds = new DataOutputStream(conn.getOutputStream());
writeFileParams();
writeStringParams();
paramsEnd();
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
conn.disconnect();
return out.toByteArray();
}
//文件上传的connection的一些必须设置
private void initConnection() throws Exception {
conn = (HttpURLConnection) this.url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000); //连接超时为10秒
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
}
//普通字符串数据
private void writeStringParams() throws Exception {
Set<String> keySet = textParams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"\r\n");
ds.writeBytes("\r\n");
ds.writeBytes(encode(value) + "\r\n");
}
}
//文件数据
private void writeFileParams() throws Exception {
Set<String> keySet = fileparams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
File value = fileparams.get(name);
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + encode(value.getName()) + "\"\r\n");
ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
ds.writeBytes("\r\n");
ds.write(getBytes(value));
ds.writeBytes("\r\n");
}
}
//获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
private String getContentType(File f) throws Exception {
// return "application/octet-stream"; // 此行不再细分是否为图片,全部作为application/octet-stream 类型
ImageInputStream imagein = ImageIO.createImageInputStream(f);
if (imagein == null) {
return "application/octet-stream";
}
Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
if (!it.hasNext()) {
imagein.close();
return "application/octet-stream";
}
imagein.close();
return "image/" + it.next().getFormatName().toLowerCase();//将FormatName返回的值转换成小写,默认为大写
}
//把文件转换成字节数组
private byte[] getBytes(File f) throws Exception {
FileInputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
//添加结尾数据
private void paramsEnd() throws Exception {
ds.writeBytes("--" + boundary + "--" + "\r\n");
ds.writeBytes("\r\n");
}
// 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
private String encode(String value) throws Exception{
return URLEncoder.encode(value, "UTF-8");
}
public RegisterForm getRegisterForm()
{
RegisterForm registerForm = new RegisterForm();
registerForm.setUserAccount("userAccount");
registerForm.setPassword("password");
registerForm.setPassword2("password2");
registerForm.setCompanyName("companyName");
registerForm.setLegalRepresentative("legalRepresentative");
registerForm.setIndustry("industry");
registerForm.setArea("area");
registerForm.setAddress("address");
// registerForm.setLongitude("longitude");
// registerForm.setLatitude("latitude");
registerForm.setPostCode("postCode");
registerForm.setTelephone("telephone");
registerForm.setMobile("mobile");
registerForm.setFax("fax");
registerForm.setUrl("url");
registerForm.setBrandName("中国");
registerForm.setCompanyScope("companyScope");
registerForm.setLogo("logo");
registerForm.setBusinessLicence("businessLicence");
registerForm.setTrademarkLicence("trademarkLicence");
registerForm.setIdentityCode("9999999");
registerForm.setEmail("email");
return registerForm;
}
public static void main(String[] args) throws Exception {
HttpPostUtil u = new HttpPostUtil("http://127.0.0.1/servlet/multiFormServlet?module=frontend.registerlogin&method=Register.register__userRegister");
u.addFileParameter("logo", new File(
"C:\\Hydrangeas.jpg"));
u.addFileParameter("businessLicence", new File(
"C:\\Hydrangeas.jpg"));
u.addFileParameter("trademarkLicence", new File(
"C:\\Hydrangeas.jpg"));
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>() {
}.getType();
Map<String, String> Params = gson.fromJson(gson.toJson(u.getRegisterForm()), type) ;
u.addAllTextParameter(Params);
byte[] b = u.send();
String result = new String(b);
System.out.println(result);
}
}
class RegisterForm{
private String userAccount;
private String password;
private String password2;
private String companyName;
private String legalRepresentative;
private String industry;
private String area;
private String address;
private String longitude;
private String latitude;
private String postCode;
private String telephone;
private String mobile;
private String fax;
private String url;
private String brandName;
private String companyScope;
private String logo;
private String businessLicence;
private String trademarkLicence;
private String identityCode;
private String email;
public String getUserAccount() {
return userAccount;
}
public String getPassword() {
return password;
}
public String getPassword2() {
return password2;
}
public String getCompanyName() {
return companyName;
}
public String getLegalRepresentative() {
return legalRepresentative;
}
public String getIndustry() {
return industry;
}
public String getArea() {
return area;
}
public String getAddress() {
return address;
}
public String getLongitude() {
return longitude;
}
public String getLatitude() {
return latitude;
}
public String getPostCode() {
return postCode;
}
public String getTelephone() {
return telephone;
}
public String getMobile() {
return mobile;
}
public String getFax() {
return fax;
}
public String getUrl() {
return url;
}
public String getBrandName() {
return brandName;
}
public String getCompanyScope() {
return companyScope;
}
public String getLogo() {
return logo;
}
public String getBusinessLicence() {
return businessLicence;
}
public String getTrademarkLicence() {
return trademarkLicence;
}
public String getIdentityCode() {
return identityCode;
}
public String getEmail() {
return email;
}
public void setUserAccount(String userAccount) {
this.userAccount = userAccount;
}
public void setPassword(String password) {
this.password = password;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public void setLegalRepresentative(String legalRepresentative) {
this.legalRepresentative = legalRepresentative;
}
public void setIndustry(String industry) {
this.industry = industry;
}
public void setArea(String area) {
this.area = area;
}
public void setAddress(String address) {
this.address = address;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public void setFax(String fax) {
this.fax = fax;
}
public void setUrl(String url) {
this.url = url;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public void setCompanyScope(String companyScope) {
this.companyScope = companyScope;
}
public void setLogo(String logo) {
this.logo = logo;
}
public void setBusinessLicence(String businessLicence) {
this.businessLicence = businessLicence;
}
public void setTrademarkLicence(String trademarkLicence) {
this.trademarkLicence = trademarkLicence;
}
public void setIdentityCode(String identityCode) {
this.identityCode = identityCode;
}
public void setEmail(String email) {
this.email = email;
}
}
接收方:
package cn.com.zt;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.nutz.json.Json;
import org.osgi.service.http.HttpContext;
import com.zte.hbs.common.bean.CommonResult;
import com.zte.hbs.common.bean.DispatchResult;
import com.zte.hbs.common.bean.JsonResult;
import com.zte.hbs.common.bean.RedirectResult;
import com.zte.hbs.common.data.Constant;
import com.zte.hbs.common.data.entity.HbsBusinessesBaseInf;
import com.zte.hbs.common.util.ConfigUtil;
import com.zte.hbs.common.util.CookieUtil;
import bee.besta.business.service.BusinessInvoker;
public class MultiFormServlet extends HttpServlet implements Constant {
private static final Logger logger = Logger.getLogger(MultiFormServlet.class);
private BusinessInvoker invoker;
private HttpContext httpContext;
private ServletFileUpload uploader;
private String savepath;
private String basepath;
public MultiFormServlet(BusinessInvoker invoker, HttpContext httpContext)
{
this.invoker = invoker;
this.httpContext = httpContext;
DiskFileItemFactory fif = new DiskFileItemFactory();
fif.setRepository(new File(ConfigUtil.getTempDir()));
fif.setSizeThreshold(1000*1000); // 1MB
uploader = new ServletFileUpload(fif);
String home = ConfigUtil.getUploadNameSpace().getHome();
savepath = home + ConfigUtil.getUploadConifg().getProperty("savePath");
File f = new File(savepath);
if (!f.isDirectory()) {
f.mkdirs();
}
basepath = ConfigUtil.getF6Conifg().getProperty("context_path");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.debug("FORM处理 -开始");
Map<String, Object> newParams = new HashMap<String, Object>();
try {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
Map<String, Object> params = req.getParameterMap();
newParams.putAll(params);
logger.debug("FORM处理 -开始");
if (ServletFileUpload.isMultipartContent(req)) {
List<FileItem> list = uploader.parseRequest(req);
for (FileItem f : list) {
String value = "";
if (!f.isFormField()) {
if (!"".equals(f.getName())) {
String ext;
if (f.getName().lastIndexOf(".")!=-1) {
ext = f.getName().substring(f.getName().lastIndexOf("."));
} else {
ext = f.getName();
}
value = System.currentTimeMillis()+ext;
File saveFile = new File(savepath + value);
f.write(saveFile);
}
}else {
value = new String(f.getString().getBytes("ISO-8859-1"), "UTF8");
value = URLDecoder.decode(value, "UTF8");
}
if (newParams.containsKey(f.getFieldName())) {
newParams.put(f.getFieldName(), newParams.get(f.getFieldName()) + ";" + value);
} else {
newParams.put(f.getFieldName(), value);
}
}
}
String module = req.getParameter("module");
String method = req.getParameter("method");
StringBuilder bid = new StringBuilder("com.zte.hbs.");
bid.append(module);
bid.append(".business.BusinessCenter4");
bid.append(method);
newParams.remove("module");
newParams.remove("method");
Object obj = invoker.invoke(bid.toString(), CookieUtil.readLoginCookie(req), newParams);
if(null!=newParams.get("identityCode")&&newParams.get("identityCode").equals("9999999"))
{
if(obj instanceof DispatchResult){
if(!((DispatchResult)obj).getContext().get("type").equals(CommonResult.ERROR))
{
resp.getWriter().write("Y");
}
}else
{
resp.getWriter().write("N");
}
}else
{
if (obj instanceof RedirectResult) {
// String url = httpContext.getResource(((RedirectResult)obj).getRedirectPath()).toString();
String url = basepath + ((RedirectResult)obj).getRedirectPath();
resp.sendRedirect(url);
} else if (obj instanceof JsonResult) {
resp.setContentType("text/plain");
resp.getWriter().write(Json.toJson(obj));
} else if (obj instanceof DispatchResult) {
String url = basepath + ((DispatchResult)obj).getDispatcher();
Map<String, Object> ctx = ((DispatchResult)obj).getContext();
for (Entry<String, Object> en : ctx.entrySet()) {
req.setAttribute(en.getKey(), en.getValue());
}
RequestDispatcher disp = req.getRequestDispatcher(url);
disp.forward(req, resp);
} else {
resp.getWriter().write(obj.toString());
}
}
logger.debug("FORM处理 -结束");
} catch (Exception e) {
logger.error("FORM处理 -失败", e);
e.printStackTrace();
resp.getWriter().println("ERROR");
throw new ServletException(e);
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
}
package com.zte.hbs.common.bean;
import java.util.HashMap;
import java.util.Map;
public class CommonResult {
public static String OK = "OK";
public static String WARN = "WARN";
public static String ERROR = "ERROR";
/**
* 消息
*/
private String message;
/**
* 类型: OK, WARN, ERROR
*/
private String type;
/**
* 附加信息
*/
private Map<String, Object> addition = new HashMap<String, Object>();
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the addition
*/
public Map<String, Object> getAddition() {
return addition;
}
public boolean isSuccess() {
return OK.equals(type);
}
public static CommonResult makeFailure(String str) {
CommonResult cr = new CommonResult();
cr.setType(ERROR);
cr.setMessage(str);
return cr;
}
public static CommonResult makeSuccess() {
CommonResult cr = new CommonResult();
cr.setType(OK);
return cr;
}
}
package com.zte.hbs.common.bean;
import java.util.HashMap;
import java.util.Map;
public class DispatchResult {
/**
* 转发地址
*/
private String dispatcher;
/**
* 转发数据
*/
private Map<String, Object> context = new HashMap<String, Object>();
/**
* @return the dispatcher
*/
public String getDispatcher() {
return dispatcher;
}
/**
* @param dispatcher the dispatcher to set
*/
public void setDispatcher(String dispatcher) {
this.dispatcher = dispatcher;
}
/**
* @return the context
*/
public Map<String, Object> getContext() {
return context;
}
/**
* @param context the context to set
*/
public void setContext(Map<String, Object> context) {
this.context = context;
}
}
package com.zte.hbs.common.bean;
import java.util.HashMap;
import java.util.Map;
public class JsonResult {
public static final String TYPE_OK = "OK";
public static final String TYPE_WARN = "WARN";
public static final String TYPE_ERROR = "ERROR";
/**
* 返回类型()
*/
private String type = TYPE_OK;
/**
* 消息
*/
private String message;
private Map<String, Object> data = new HashMap<String, Object>();
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the data
*/
public Map<String, Object> getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(Map<String, Object> data) {
this.data = data;
}
}
package com.zte.hbs.common.bean;
import bee.besta.business.service.Passport;
public class RedirectResult {
private Passport p;
/**
* 重定向地址
*/
private String redirectPath;
/**
* @return the redirectPath
*/
public String getRedirectPath() {
return redirectPath;
}
/**
* @param redirectPath the redirectPath to set
*/
public void setRedirectPath(String redirectPath) {
this.redirectPath = redirectPath;
}
public Passport getP() {
return p;
}
public void setP(Passport p) {
this.p = p;
}
}
package com.zte.hbs.common.data;
public interface Constant {
/**
* 已登陆用户信息(前台)
*/
public static final String TOKEN = "_hbs_token_";
public static final String SESSION_CURRENT_USER_KEY = "_hbs_user_";
public static final String SESSION_CURRENT_COMPANY_USER_ID_KEY = "_hbs_company_user_id_";
public static final String SESSION_SSO_INFO = "_sso_Info_";
public static final String SESSION_ADDITION_INFO = "_addition_Info_";
public static final String SESSION_CURRENT_COMPANY_KEY = "_hbs_company_";
public static final String SESSION_CAPTCHA = "_captcha_";
public static final String ADDITION_IS_COMPANY_USER_KEY = "_is_company_user_";
/**
* 含文件上传模版
*/
public static final String REQ_MULTI_PARAMS = "multiList";
/**
* 已登陆用户信息(后台)
*/
public static final String SESSION_CURRENT_SYSUSER_KEY = "_hbs_sysuser_";
public static final String SESSION_CURRENT_ROLE_RESP_KEY = "_hbs_role_resp_";
/**后台每页显示最大数**/
public static final int BACKEND_PAGE_MAX_RECORDS = 10;
/**DATA_FROM 常量**/
public static final String BACKEND_DATA_FROM = "TRL_AIYOU";
/**图片验证种类**/
public static final int MAX_SIZE = 1;
public static final int FIXED_SIZE = 2;
public static final int MAX_BYTES = 3;
}
package com.zte.hbs.common.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import com.zte.hbs.common.service.JbpmManagerService;
import bee.base.service.BaseService;
import bee.base.service.Namespace;
public class ConfigUtil {
private static BaseService baseService;
public static void setBaseService(BaseService _baseService)
{
baseService = _baseService;
}
public static Properties getUploadConifg() {
return baseService.getNamespace("upload").getConfigAsProperties("Config");
}
public static Properties getRestapiConifg() {
String pp =baseService.getNamespace("restapi").getHome();
return baseService.getNamespace("restapi").getConfigAsProperties("Config");
}
public static Properties getMailConifg() {
if (baseService == null) {
Properties props = new Properties();
try {
props.load(new FileInputStream("E:\\China_Business\\ZTE1\\01.prj\\04.PG\\hbs\\base\\config\\mail.Config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
return baseService.getNamespace("mail").getConfigAsProperties("Config");
}
public static String getTempDir() {
return baseService.getNamespace("base").getTempDir();
}
public static Namespace getUploadNameSpace() {
return baseService.getNamespace("upload");
}
public static Properties getF6Conifg() {
return baseService.getNamespace("f6").getConfigAsProperties("F6Config");
}
public static Properties getVolConifg() {
return baseService.getNamespace("vol").getConfigAsProperties("Config");
}
public static void storeConifg(String nameSpace,String configAs,String key, String value) {
baseService.getNamespace(nameSpace).getConfigAsProperties(configAs).setProperty(key, value);
}
public static Properties getWsdlParamAsProperties() {
if (baseService == null) {
Properties props = new Properties();
try {
props.load(new FileInputStream("D:\\java\\eclipse_soa\\hbs\\base\\config\\wsdl.Config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
return baseService.getNamespace("wsdl").getConfigAsProperties("Config");
}
public static String getWsdlParamAsProperties(String prop) {
return getWsdlParamAsProperties().getProperty(prop);
}
public static Properties getUrlConifg() {
return baseService.getNamespace("url").getConfigAsProperties("Config");
}
/**
* @return the jbpmManagerService
*/
public static JbpmManagerService getJbpmManagerService() {
return jbpmManagerService;
}
/**
* @param jbpmManagerService the jbpmManagerService to set
*/
public static void setJbpmManagerService(JbpmManagerService jbpmManagerService) {
ConfigUtil.jbpmManagerService = jbpmManagerService;
}
private static JbpmManagerService jbpmManagerService;
}
// Source File Name: CookieUtil.java
package com.zte.hbs.common.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class CookieUtil
{
public CookieUtil()
{
}
public static String readCookie(HttpServletRequest req, String key)
{
Cookie cookies[] = req.getCookies();
Cookie acookie[];
if (cookies != null) {
int j = (acookie = cookies).length;
for(int i = 0; i < j; i++)
{
Cookie cookie = acookie[i];
if(key.equals(cookie.getName()))
return unescape(cookie.getValue());
}
}
return "";
}
public static String readLoginCookie(HttpServletRequest req)
{
return readCookie(req, "hbs_p");
}
public static String unescape(String src)
{
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length());
int lastPos = 0;
int pos = 0;
while(lastPos < src.length())
{
pos = src.indexOf("%", lastPos);
if(pos == lastPos)
{
if(src.charAt(pos + 1) == ‘u‘)
{
char ch = (char)Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
} else
{
char ch = (char)Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
} else
if(pos == -1)
{
tmp.append(src.substring(lastPos));
lastPos = src.length();
} else
{
tmp.append(src.substring(lastPos, pos));
lastPos = pos;
}
}
return tmp.toString();
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。