一、Maven引入httpclient、httpmime、httpclient-cache
二、表单内容
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
<input type="text" name="param1" value="value1"/>
<input type="text" name="param1" value="value1"/>
<input type="file" name="file" value="value1"/>
<input type="submit" value="submit"/>
</form>
三、代码内容
HttpClient httpClient = new DefaultHttpClient();
HttpServletRequest request = ServletActionContext.getRequest();
String sessionId = request.getRequestedSessionId();
Enumeration paramNames = request.getParameterNames();
MultipartEntity multipartEntity = new MultipartEntity();
try {
while (paramNames.hasMoreElements()) {
String param = (String) paramNames.nextElement();
String value = request.getParameter(param);
StringBody body = new StringBody(value, Charset.forName("UTF-8"));
multipartEntity.addPart(param, body);
}
if (installationPackage != null) {
multipartEntity.addPart("installationPackage", new InputStreamBody(new FileInputStream(installationPackage), installationPackageFileName));
}
if (ico != null) {
multipartEntity.addPart("ico", new InputStreamBody(new FileInputStream(ico), icoFileName));
}
String url = http://localhost:8080/management/StatisticsAction_uploadVersion";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Cookie","JSESSIONID="+sessionId);
httpPost.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
JSONObject object = (JSONObject) JSONObject.parse(EntityUtils.toString(resEntity));
return (boolean) object.get("success");
}
}
} finally {
try {
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
logger.error(e);
}
}