Search in sources :

Example 86 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest 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 87 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest 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 88 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project Lucee by lucee.

the class HTTPResponse4Impl method getTargetURL.

public URL getTargetURL() {
    URL start = getURL();
    HttpUriRequest req = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
    URI uri = req.getURI();
    String path = uri.getPath();
    String query = uri.getQuery();
    if (!StringUtil.isEmpty(query))
        path += "?" + query;
    URL _url = start;
    try {
        _url = new URL(start.getProtocol(), start.getHost(), start.getPort(), path);
    } catch (MalformedURLException e) {
    }
    return _url;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) MalformedURLException(java.net.MalformedURLException) URI(java.net.URI) URL(java.net.URL)

Example 89 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project cas by apereo.

the class HttpUtils method execute.

/**
 * Execute http request and produce a response.
 *
 * @param url               the url
 * @param method            the method
 * @param basicAuthUsername the basic auth username
 * @param basicAuthPassword the basic auth password
 * @param parameters        the parameters
 * @param headers           the headers
 * @param entity            the entity
 * @return the http response
 */
public static HttpResponse execute(final String url, final String method, final String basicAuthUsername, final String basicAuthPassword, final Map<String, String> parameters, final Map<String, String> headers, final String entity) {
    try {
        final HttpClient client = buildHttpClient(basicAuthUsername, basicAuthPassword);
        final URI uri = buildHttpUri(url, parameters);
        final HttpUriRequest request;
        switch(method.toLowerCase()) {
            case "post":
                request = new HttpPost(uri);
                if (StringUtils.isNotBlank(entity)) {
                    final StringEntity stringEntity = new StringEntity(entity);
                    ((HttpPost) request).setEntity(stringEntity);
                }
                break;
            case "delete":
                request = new HttpDelete(uri);
                break;
            case "get":
            default:
                request = new HttpGet(uri);
                break;
        }
        headers.forEach(request::addHeader);
        return client.execute(request);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException)

Example 90 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project openhab1-addons by openhab.

the class StreamClientImpl method sendRequest.

@Override
public StreamResponseMessage sendRequest(StreamRequestMessage requestMessage) {
    final UpnpRequest requestOperation = requestMessage.getOperation();
    log.fine("Preparing HTTP request message with method '" + requestOperation.getHttpMethodName() + "': " + requestMessage);
    try {
        // Create the right HTTP request
        HttpUriRequest httpRequest = createHttpRequest(requestMessage, requestOperation);
        // Set all the headers on the request
        httpRequest.setParams(getRequestParams(requestMessage));
        HeaderUtil.add(httpRequest, requestMessage.getHeaders());
        log.fine("Sending HTTP request: " + httpRequest.getURI());
        return httpClient.execute(httpRequest, createResponseHandler());
    } catch (MethodNotSupportedException ex) {
        log.warning("Request aborted: " + ex.toString());
        return null;
    } catch (ClientProtocolException ex) {
        log.warning("HTTP protocol exception executing request: " + requestMessage);
        log.warning("Cause: " + Exceptions.unwrap(ex));
        return null;
    } catch (IOException ex) {
        // Don't log stacktrace
        log.fine("Client connection was aborted: " + ex.getMessage());
        return null;
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) UpnpRequest(org.teleal.cling.model.message.UpnpRequest) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Aggregations

HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)185 Test (org.junit.Test)62 TestRequest (com.android.volley.mock.TestRequest)52 HttpGet (org.apache.http.client.methods.HttpGet)45 URI (java.net.URI)43 HttpResponse (org.apache.http.HttpResponse)41 HttpEntity (org.apache.http.HttpEntity)38 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)36 HttpPost (org.apache.http.client.methods.HttpPost)22 IOException (java.io.IOException)19 Header (org.apache.http.Header)18 JSONObject (org.json.JSONObject)18 BufferedReader (java.io.BufferedReader)17 InputStreamReader (java.io.InputStreamReader)17 PrintWriter (java.io.PrintWriter)17 StringWriter (java.io.StringWriter)17 HttpHost (org.apache.http.HttpHost)13 HttpPut (org.apache.http.client.methods.HttpPut)12 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)11 StringEntity (org.apache.http.entity.StringEntity)10