您的位置:首页 > 理论基础 > 计算机网络

Java发送Http请求,模拟表单上传文件

2018-02-24 13:02 525 查看
一、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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java HttpClient Http Struts2