Search in sources :

Example 26 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project 12306-hunter by xautlx.

the class HttpClientService method postHttpRequest.

/**
	 * POST请求
	 * @param httpclient
	 * @param url
	 * @param parameters
	 * @param cookieData
	 * @return
	 */
private HttpResponse postHttpRequest(HttpClient httpclient, String url, List<NameValuePair> parameters, Map<String, String> cookieData) {
    try {
        logger.debug("------------------------------------------------------------------------");
        logger.debug("POST URL: " + url);
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)");
        if (cookieData != null) {
            boolean first = true;
            StringBuilder cookie = new StringBuilder();
            for (Map.Entry<String, String> me : cookieData.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    cookie.append(";");
                }
                cookie.append(me.getKey() + "=" + me.getValue());
            }
            post.setHeader("Cookie", cookie.toString());
        }
        if (parameters != null) {
            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
            post.setEntity(uef);
        }
        if (logger.isDebugEnabled()) {
            if (parameters != null) {
                logger.debug(" + Request parameters: ");
                for (NameValuePair param : parameters) {
                    logger.debug("   - " + param.getName() + " : " + param.getValue());
                }
            }
            logger.debug(" + Request headers: ");
            for (Header header : post.getAllHeaders()) {
                logger.debug("   - " + header.getName() + " : " + header.getValue());
            }
        }
        HttpResponse response = httpclient.execute(post);
        if (logger.isDebugEnabled()) {
            logger.debug(" + Response headers: ");
            for (Header header : response.getAllHeaders()) {
                logger.debug("   - " + header.getName() + " : " + header.getValue());
            }
        }
        logger.debug("***********************************************************************");
        return response;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) Header(org.apache.http.Header) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HashMap(java.util.HashMap) Map(java.util.Map) CertificateException(java.security.cert.CertificateException)

Example 27 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project afinal by yangfuhai.

the class AjaxParams method getEntity.

/**
     * Returns an HttpEntity containing all request parameters
     */
public HttpEntity getEntity() {
    HttpEntity entity = null;
    if (!fileParams.isEmpty()) {
        MultipartEntity multipartEntity = new MultipartEntity();
        // Add string params
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            multipartEntity.addPart(entry.getKey(), entry.getValue());
        }
        // Add file params
        int currentIndex = 0;
        int lastIndex = fileParams.entrySet().size() - 1;
        for (ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
            FileWrapper file = entry.getValue();
            if (file.inputStream != null) {
                boolean isLast = currentIndex == lastIndex;
                if (file.contentType != null) {
                    multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, file.contentType, isLast);
                } else {
                    multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, isLast);
                }
            }
            currentIndex++;
        }
        entity = multipartEntity;
    } else {
        try {
            entity = new UrlEncodedFormEntity(getParamsList(), ENCODING);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return entity;
}
Also used : HttpEntity(org.apache.http.HttpEntity) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 28 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 29 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project opennms by OpenNMS.

the class HttpCollector method buildPostMethod.

private static HttpPost buildPostMethod(final URI uri, final HttpCollectorAgent collectorAgent) {
    HttpPost method = new HttpPost(uri);
    List<NameValuePair> postParams = buildRequestParameters(collectorAgent);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8);
    method.setEntity(entity);
    return method;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 30 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project opennms by OpenNMS.

the class RequestTracker method getClientWrapper.

public synchronized HttpClientWrapper getClientWrapper() {
    if (m_clientWrapper == null) {
        m_clientWrapper = HttpClientWrapper.create().setSocketTimeout(m_timeout).setConnectionTimeout(m_timeout).setRetries(m_retries).useBrowserCompatibleCookies().dontReuseConnections();
        final HttpPost post = new HttpPost(m_baseURL + "/REST/1.0/user/" + m_user);
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("user", m_user));
        params.add(new BasicNameValuePair("pass", m_password));
        CloseableHttpResponse response = null;
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
            post.setEntity(entity);
            response = m_clientWrapper.execute(post);
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode != HttpStatus.SC_OK) {
                throw new RequestTrackerException("Received a non-200 response code from the server: " + responseCode);
            } else {
                if (response.getEntity() != null) {
                    EntityUtils.consume(response.getEntity());
                }
                LOG.warn("got user session for username: {}", m_user);
            }
        } catch (final Exception e) {
            LOG.warn("Unable to get session (by requesting user details)", e);
        } finally {
            m_clientWrapper.close(response);
        }
    }
    return m_clientWrapper;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException)

Aggregations

UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)127 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)105 HttpPost (org.apache.http.client.methods.HttpPost)99 NameValuePair (org.apache.http.NameValuePair)94 ArrayList (java.util.ArrayList)91 HttpResponse (org.apache.http.HttpResponse)71 IOException (java.io.IOException)45 HttpEntity (org.apache.http.HttpEntity)39 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)30 ClientProtocolException (org.apache.http.client.ClientProtocolException)27 UnsupportedEncodingException (java.io.UnsupportedEncodingException)23 Test (org.junit.Test)20 HttpClient (org.apache.http.client.HttpClient)19 HttpGet (org.apache.http.client.methods.HttpGet)19 JSONObject (org.json.JSONObject)17 Map (java.util.Map)16 TestHttpClient (io.undertow.testutils.TestHttpClient)14 Header (org.apache.http.Header)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 HashMap (java.util.HashMap)12