When programmatically presenting a form created by JSF, you need to make sure that you consider the following 3 things:
- Maintain an HTTP session (of course, if stateful JSF server side state is enabled on the website).
- Send the name-value pair of the hidden field
javax.faces.ViewState. - - , .
, , . "" . :
- GET .
- cookie JSESSIONID.
javax.faces.ViewState . (, , , ), submit. / j_id.multipart/form-data POST.- cookie JSESSIONID (
null) . - -
javax.faces.ViewState . - .
HTTP . Java SE API java.net.URLConnection , . , Apache HttpClient HTTP- cookie Jsoup HTML.
kickoff, , <form> ( CSS Jsoup):
String url = "http://localhost:8088/playground/test.xhtml";
String viewStateName = "javax.faces.ViewState";
String submitButtonValue = "Upload";
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
HttpGet httpGet = new HttpGet(url);
HttpResponse getResponse = httpClient.execute(httpGet, httpContext);
Document document = Jsoup.parse(EntityUtils.toString(getResponse.getEntity()));
String viewStateValue = document.select("input[type=hidden][name=" + viewStateName + "]").val();
String uploadFieldName = document.select("input[type=file]").attr("name");
String submitButtonName = document.select("input[type=submit][value=" + submitButtonValue + "]").attr("name");
File file = new File("/path/to/file/you/want/to/upload.ext");
InputStream fileContent = new FileInputStream(file);
String fileContentType = "application/octet-stream";
String fileName = file.getName();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart(uploadFieldName, new InputStreamBody(fileContent, fileContentType, fileName));
entity.addPart(viewStateName, new StringBody(viewStateValue));
entity.addPart(submitButtonName, new StringBody(submitButtonValue));
httpPost.setEntity(entity);
HttpResponse postResponse = httpClient.execute(httpPost, httpContext);