Search in sources :

Example 76 with NameValuePair

use of org.apache.http.NameValuePair in project opennms by OpenNMS.

the class HttpNorthbounder method forwardAlarms.

/* (non-Javadoc)
     * @see org.opennms.netmgt.alarmd.api.support.AbstractNorthbounder#forwardAlarms(java.util.List)
     */
@Override
public void forwardAlarms(List<NorthboundAlarm> alarms) throws NorthbounderException {
    LOG.info("Forwarding {} alarms", alarms.size());
    // Need a configuration bean for these
    int connectionTimeout = 3000;
    int socketTimeout = 3000;
    Integer retryCount = Integer.valueOf(3);
    URI uri = m_config.getURI();
    final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(connectionTimeout).setSocketTimeout(socketTimeout).setRetries(retryCount).useBrowserCompatibleCookies();
    if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
        clientWrapper.setVirtualHost(m_config.getVirtualHost());
    }
    if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
        clientWrapper.setUserAgent(m_config.getUserAgent());
    }
    if ("https".equals(uri.getScheme())) {
        try {
            clientWrapper.useRelaxedSSL("https");
        } catch (final GeneralSecurityException e) {
            throw new NorthbounderException("Failed to configure HTTP northbounder for relaxed SSL.", e);
        }
    }
    HttpUriRequest method = null;
    if (HttpMethod.POST == (m_config.getMethod())) {
        HttpPost postMethod = new HttpPost(uri);
        // TODO: need to configure these
        List<NameValuePair> postParms = new ArrayList<>();
        // FIXME:do this for now
        NameValuePair p = new BasicNameValuePair("foo", "bar");
        postParms.add(p);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParms, StandardCharsets.UTF_8);
        postMethod.setEntity(formEntity);
        HttpEntity entity = null;
        try {
            // I have no idea what I'm doing here ;)
            entity = new StringEntity("XML HERE");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        postMethod.setEntity(entity);
        method = postMethod;
    } else if (HttpMethod.GET == m_config.getMethod()) {
        // TODO: need to configure these
        // List<NameValuePair> getParms = null;
        method = new HttpGet(uri);
    }
    HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
    clientWrapper.setVersion(httpVersion);
    HttpResponse response = null;
    try {
        response = clientWrapper.execute(method);
        int code = response.getStatusLine().getStatusCode();
        HttpResponseRange range = new HttpResponseRange("200-399");
        if (!range.contains(code)) {
            LOG.debug("response code out of range for uri:{}.  Expected {} but received {}", uri, range, code);
            throw new NorthbounderException("response code out of range for uri:" + uri + ".  Expected " + range + " but received " + code);
        }
        LOG.debug("HTTP Northbounder received response: {}", response.getStatusLine().getReasonPhrase());
    } catch (final ClientProtocolException e) {
        throw new NorthbounderException(e);
    } catch (final IOException e) {
        throw new NorthbounderException(e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) GeneralSecurityException(java.security.GeneralSecurityException) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseRange(org.opennms.core.utils.HttpResponseRange) StringEntity(org.apache.http.entity.StringEntity) NorthbounderException(org.opennms.netmgt.alarmd.api.NorthbounderException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) HttpVersion(org.apache.http.HttpVersion)

Example 77 with NameValuePair

use of org.apache.http.NameValuePair in project opennms by OpenNMS.

the class HttpNotificationStrategy method send.

/* (non-Javadoc)
     * @see org.opennms.netmgt.notifd.NotificationStrategy#send(java.util.List)
     */
/**
 * {@inheritDoc}
 */
@Override
public int send(List<Argument> arguments) {
    m_arguments = arguments;
    String url = getUrl();
    if (url == null) {
        LOG.warn("send: url argument is null, HttpNotification requires a URL");
        return 1;
    }
    final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(3000).setSocketTimeout(3000).useSystemProxySettings();
    HttpUriRequest method = null;
    final List<NameValuePair> posts = getPostArguments();
    if (posts == null) {
        method = new HttpGet(url);
        LOG.info("send: No \"post-\" arguments..., continuing with an HTTP GET using URL: {}", url);
    } else {
        LOG.info("send: Found \"post-\" arguments..., continuing with an HTTP POST using URL: {}", url);
        for (final NameValuePair post : posts) {
            LOG.debug("send: post argument: {} = {}", post.getName(), post.getValue());
        }
        method = new HttpPost(url);
        final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(posts, StandardCharsets.UTF_8);
        ((HttpPost) method).setEntity(entity);
    }
    String contents = null;
    int statusCode = -1;
    try {
        CloseableHttpResponse response = clientWrapper.execute(method);
        statusCode = response.getStatusLine().getStatusCode();
        contents = EntityUtils.toString(response.getEntity());
        LOG.info("send: Contents is: {}", contents);
    } catch (IOException e) {
        LOG.error("send: IO problem with HTTP post/response: {}", e);
        throw new RuntimeException("Problem with HTTP post: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
    doSql(contents);
    return statusCode;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException)

Example 78 with NameValuePair

use of org.apache.http.NameValuePair in project opennms by OpenNMS.

the class HttpNotificationStrategy method getPostArguments.

private List<NameValuePair> getPostArguments() {
    List<Argument> args = getArgsByPrefix("post-");
    List<NameValuePair> retval = new ArrayList<>();
    for (Argument arg : args) {
        String argSwitch = arg.getSwitch().substring("post-".length());
        if (arg.getValue() == null) {
            arg.setValue("");
        }
        retval.add(new BasicNameValuePair(argSwitch, getValue(arg.getValue())));
    }
    return retval;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) Argument(org.opennms.netmgt.model.notifd.Argument) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList)

Example 79 with NameValuePair

use of org.apache.http.NameValuePair in project Lucee by lucee.

the class HTTPEngine4Impl method setFormFields.

private static void setFormFields(HttpUriRequest request, Map<String, String> formfields, String charset) throws IOException {
    if (!CollectionUtil.isEmpty(formfields)) {
        if (!(request instanceof HttpPost))
            throw new IOException("form fields are only suppported for post request");
        HttpPost post = (HttpPost) request;
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator<Entry<String, String>> it = formfields.entrySet().iterator();
        Entry<String, String> e;
        while (it.hasNext()) {
            e = it.next();
            list.add(new BasicNameValuePair(e.getKey(), e.getValue()));
        }
        if (StringUtil.isEmpty(charset))
            charset = ((PageContextImpl) ThreadLocalPageContext.get()).getWebCharset().name();
        post.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(list, charset));
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Entry(java.util.Map.Entry) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 80 with NameValuePair

use of org.apache.http.NameValuePair in project SneakerBot by Penor.

the class Supreme method checkout.

public boolean checkout(String variant) {
    HttpPost request = new HttpPost("https://www.supremenewyork.com/checkout.json");
    HttpResponse response = null;
    request.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_3 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G34");
    request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    request.setHeader("Accept-Encoding", "gzip, deflate, sdch");
    request.setHeader("Accept-Language", "en-US,en;q=0.8");
    request.setHeader("Connection", "keep-alive");
    request.setHeader("Host", "www.supremenewyork.com");
    request.setHeader("Upgrade-Insecure-Requests", "1");
    List<NameValuePair> data = generateCheckout(variant);
    try {
        request.setEntity(new UrlEncodedFormEntity(data));
        response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null) result.append(line);
        in.close();
        print(result.toString());
        if (response.getStatusLine().getStatusCode() == 200) {
            JSONObject checkoutJson = new JSONObject(result.toString());
            if (!checkoutJson.getString("status").toLowerCase().equals("failed")) {
                itemCarted = true;
                return true;
            } else
                print("Checkout status: " + checkoutJson.getString("status"));
        } else
            print("Status Code: " + response.getStatusLine().getStatusCode() + " Body: " + result.toString());
        // sleep random time 1.5-3 secs
        sleep(new Random().nextInt((int) (3500L - 1500L) + 1) + 1500L);
    } catch (Exception e) {
        if (debug)
            e.printStackTrace();
        else {
            String name = e.getClass().getName();
            if (!name.contains("SocketTimeoutException"))
                print("[Exception - addToCart(productId, variant)] -> " + name);
        }
    } finally {
        if (request != null)
            request.releaseConnection();
        try {
            if (response != null && response.getEntity() != null)
                EntityUtils.consume(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) JSONObject(org.json.JSONObject) Random(java.util.Random) BufferedReader(java.io.BufferedReader) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

NameValuePair (org.apache.http.NameValuePair)713 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)592 ArrayList (java.util.ArrayList)478 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)256 HttpPost (org.apache.http.client.methods.HttpPost)218 HttpResponse (org.apache.http.HttpResponse)150 IOException (java.io.IOException)125 HttpEntity (org.apache.http.HttpEntity)108 Test (org.junit.Test)85 URI (java.net.URI)79 Map (java.util.Map)72 HashMap (java.util.HashMap)68 HttpGet (org.apache.http.client.methods.HttpGet)66 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)59 UnsupportedEncodingException (java.io.UnsupportedEncodingException)58 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)55 URISyntaxException (java.net.URISyntaxException)52 Document (org.jsoup.nodes.Document)51 URIBuilder (org.apache.http.client.utils.URIBuilder)50 HttpClient (org.apache.http.client.HttpClient)46