use of org.apache.http.client.entity.UrlEncodedFormEntity in project DrupalCloud by INsReady.
the class RESTServerClient method callPost.
public InputStreamReader callPost(String url, BasicNameValuePair[] parameters) throws ServiceNotAvailableException, ClientProtocolException, IOException {
mSERVERPOST = new HttpPost(url);
mPairs.clear();
// Call "X-CSRF-Token" token from service
if (getToken() != null) {
mSERVERPOST.setHeader("X-CSRF-Token", getToken());
}
if (getSession() != null) {
mSERVERPOST.setHeader("Cookie", getSession());
}
for (int i = 0; i < parameters.length; i++) {
mPairs.add(parameters[i]);
}
mSERVERPOST.setEntity(new UrlEncodedFormEntity(mPairs));
HttpResponse response = mClient.execute(mSERVERPOST);
InputStream is = response.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
return isr;
}
use of org.apache.http.client.entity.UrlEncodedFormEntity in project appsly-android-rest by 47deg.
the class JacksonHttpFormValuesConverter method toRequestBody.
@Override
@SuppressWarnings("unchecked")
public <T> HttpEntity toRequestBody(T object, String contentType) {
Logger.d("JacksonHttpFormValuesConverter.toRequestBody: object: " + object);
try {
HttpEntity entity = null;
List<NameValuePair> vals = new ArrayList<NameValuePair>();
if (HeaderUtils.CONTENT_TYPE_FORM_URL_ENCODED.startsWith(contentType)) {
Map<String, Object> props = mapper.convertValue(object, Map.class);
for (Map.Entry<String, Object> formPartEntry : props.entrySet()) {
if (formPartEntry.getValue() != null) {
vals.add(new BasicNameValuePair(formPartEntry.getKey(), formPartEntry.getValue().toString()));
}
}
entity = new UrlEncodedFormEntity(vals);
} else if (HeaderUtils.CONTENT_TYPE_MULTIPART_FORM_DATA.startsWith(contentType)) {
Map<String, Object> props = mapper.convertValue(object, Map.class);
MultipartEntity multipartEntity = new MultipartEntity(null);
for (Map.Entry<String, Object> formPartEntry : props.entrySet()) {
if (formPartEntry.getValue() != null) {
if (formPartEntry.getValue() instanceof FileFormField) {
FileFormField fileFormField = (FileFormField) formPartEntry.getValue();
multipartEntity.addPart(formPartEntry.getKey(), fileFormField.getFile(), fileFormField.getContentType());
} else {
multipartEntity.addPart(formPartEntry.getKey(), formPartEntry.getValue().toString());
}
}
}
entity = multipartEntity;
}
return entity;
} catch (UnsupportedEncodingException e) {
throw new SerializationException(e);
}
}
use of org.apache.http.client.entity.UrlEncodedFormEntity in project crawler4j by yasserg.
the class PageFetcher method doFormLogin.
/**
* FORM authentication<br/>
* Official Example:
* https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http
* /examples/client/ClientFormLogin.java
*/
private void doFormLogin(FormAuthInfo authInfo) {
logger.info("FORM authentication for: " + authInfo.getLoginTarget());
String fullUri = authInfo.getProtocol() + "://" + authInfo.getHost() + ":" + authInfo.getPort() + authInfo.getLoginTarget();
HttpPost httpPost = new HttpPost(fullUri);
List<NameValuePair> formParams = new ArrayList<>();
formParams.add(new BasicNameValuePair(authInfo.getUsernameFormStr(), authInfo.getUsername()));
formParams.add(new BasicNameValuePair(authInfo.getPasswordFormStr(), authInfo.getPassword()));
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(entity);
httpClient.execute(httpPost);
logger.debug("Successfully Logged in with user: " + authInfo.getUsername() + " to: " + authInfo.getHost());
} catch (UnsupportedEncodingException e) {
logger.error("Encountered a non supported encoding while trying to login to: " + authInfo.getHost(), e);
} catch (ClientProtocolException e) {
logger.error("While trying to login to: " + authInfo.getHost() + " - Client protocol not supported", e);
} catch (IOException e) {
logger.error("While trying to login to: " + authInfo.getHost() + " - Error making request", e);
}
}
use of org.apache.http.client.entity.UrlEncodedFormEntity in project wildfly by wildfly.
the class AbstractWebSecurityFORMTestCase method makeCall.
// Protected methods -----------------------------------------------------
/**
* Makes a HTTP request to the protected web application.
*
* @param user
* @param pass
* @param expectedStatusCode
* @throws Exception
* @see WebSecurityPasswordBasedBase#makeCall(java.lang.String, java.lang.String,
* int)
*/
@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
String req = url.toExternalForm() + "secured/";
HttpGet httpget = new HttpGet(req);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
EntityUtils.consume(entity);
}
// We should get the Login Page
StatusLine statusLine = response.getStatusLine();
LOGGER.trace("Login form get: " + statusLine);
assertEquals(200, statusLine.getStatusCode());
LOGGER.trace("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
LOGGER.trace("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
LOGGER.trace("- " + cookies.get(i).toString());
}
}
req = url.toExternalForm() + "secured/j_security_check";
// We should now login with the user name and password
HttpPost httpPost = new HttpPost(req);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("j_username", user));
nvps.add(new BasicNameValuePair("j_password", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
response = httpclient.execute(httpPost);
entity = response.getEntity();
if (entity != null) {
EntityUtils.consume(entity);
}
statusLine = response.getStatusLine();
// Post authentication - we have a 302
assertEquals(302, statusLine.getStatusCode());
Header locationHeader = response.getFirstHeader("Location");
String location = locationHeader.getValue();
HttpGet httpGet = new HttpGet(location);
response = httpclient.execute(httpGet);
entity = response.getEntity();
if (entity != null) {
EntityUtils.consume(entity);
}
LOGGER.trace("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
LOGGER.trace("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
LOGGER.trace("- " + cookies.get(i).toString());
}
}
// Either the authentication passed or failed based on the expected status code
statusLine = response.getStatusLine();
assertEquals(expectedStatusCode, statusLine.getStatusCode());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
use of org.apache.http.client.entity.UrlEncodedFormEntity in project wildfly by wildfly.
the class FormAuthUnitTestCase method testPostDataFormAuth.
/**
* Test that a post from an unsecured form to a secured servlet does not
* loose its data during the redirect to the form login.
*/
@Test
@OperateOnDeployment("form-auth.war")
public void testPostDataFormAuth() throws Exception {
log.trace("+++ testPostDataFormAuth");
URL url = new URL(baseURLNoAuth + "unsecure_form.html");
HttpGet httpget = new HttpGet(url.toURI());
log.trace("Executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
Header[] errorHeaders = response.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
EntityUtils.consume(response.getEntity());
// Submit the form to /restricted/SecuredPostServlet
HttpPost restrictedPost = new HttpPost(baseURLNoAuth + "restricted/SecuredPostServlet");
List<NameValuePair> restrictedParams = new ArrayList<NameValuePair>();
restrictedParams.add(new BasicNameValuePair("checkParam", "123456"));
restrictedPost.setEntity(new UrlEncodedFormEntity(restrictedParams, "UTF-8"));
log.trace("Executing request " + restrictedPost.getRequestLine());
HttpResponse restrictedResponse = httpclient.execute(restrictedPost);
statusCode = restrictedResponse.getStatusLine().getStatusCode();
errorHeaders = restrictedResponse.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
HttpEntity entity = restrictedResponse.getEntity();
if ((entity != null) && (entity.getContentLength() > 0)) {
String body = EntityUtils.toString(entity);
assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
} else {
fail("Empty body in response");
}
String sessionID = null;
for (Cookie k : httpclient.getCookieStore().getCookies()) {
if (k.getName().equalsIgnoreCase("JSESSIONID"))
sessionID = k.getValue();
}
log.trace("Saw JSESSIONID=" + sessionID);
// Submit the login form
HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("j_username", "user1"));
formparams.add(new BasicNameValuePair("j_password", "password1"));
formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
log.trace("Executing request " + formPost.getRequestLine());
HttpResponse postResponse = httpclient.execute(formPost);
statusCode = postResponse.getStatusLine().getStatusCode();
errorHeaders = postResponse.getHeaders("X-NoJException");
assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
EntityUtils.consume(postResponse.getEntity());
// Follow the redirect to the SecureServlet
Header location = postResponse.getFirstHeader("Location");
URL indexURI = new URL(location.getValue());
HttpGet war1Index = new HttpGet(indexURI.toURI());
log.trace("Executing request " + war1Index.getRequestLine());
HttpResponse war1Response = httpclient.execute(war1Index);
statusCode = war1Response.getStatusLine().getStatusCode();
errorHeaders = war1Response.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
HttpEntity war1Entity = war1Response.getEntity();
if ((war1Entity != null) && (entity.getContentLength() > 0)) {
String body = EntityUtils.toString(war1Entity);
if (body.indexOf("j_security_check") > 0)
fail("Get of " + indexURI + " redirected to login page");
} else {
fail("Empty body in response");
}
}
Aggregations