Search in sources :

Example 36 with UrlEncodedFormEntity

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;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) SuppressLint(android.annotation.SuppressLint)

Example 37 with UrlEncodedFormEntity

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);
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) SerializationException(ly.apps.android.rest.exceptions.SerializationException) HttpEntity(org.apache.http.HttpEntity) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) Map(java.util.Map)

Example 38 with UrlEncodedFormEntity

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);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 39 with UrlEncodedFormEntity

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();
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) StatusLine(org.apache.http.StatusLine) Header(org.apache.http.Header) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 40 with UrlEncodedFormEntity

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");
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URL(java.net.URL) Header(org.apache.http.Header) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) OperateOnDeployment(org.jboss.arquillian.container.test.api.OperateOnDeployment) Test(org.junit.Test)

Aggregations

UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)134 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)111 HttpPost (org.apache.http.client.methods.HttpPost)105 NameValuePair (org.apache.http.NameValuePair)100 ArrayList (java.util.ArrayList)96 HttpResponse (org.apache.http.HttpResponse)74 IOException (java.io.IOException)47 HttpEntity (org.apache.http.HttpEntity)40 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)31 ClientProtocolException (org.apache.http.client.ClientProtocolException)27 UnsupportedEncodingException (java.io.UnsupportedEncodingException)26 HttpClient (org.apache.http.client.HttpClient)20 Test (org.junit.Test)20 HttpGet (org.apache.http.client.methods.HttpGet)19 Map (java.util.Map)18 JSONObject (org.json.JSONObject)18 TestHttpClient (io.undertow.testutils.TestHttpClient)14 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 HashMap (java.util.HashMap)13 Header (org.apache.http.Header)13