Search in sources :

Example 66 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity 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 67 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity 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 68 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project Talon-for-Twitter by klinker24.

the class TwitLongerHelper method postToTwitLonger.

/**
 * Posts the status to twitlonger
 * @return returns an object containing the shortened text and the id for the twitlonger url
 */
public TwitLongerStatus postToTwitLonger() {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("X-API-KEY", TWITLONGER_API_KEY);
        post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("content", tweetText));
        if (replyToId != 0) {
            nvps.add(new BasicNameValuePair("reply_to_id", String.valueOf(replyToId)));
        } else if (replyToScreenname != null) {
            nvps.add(new BasicNameValuePair("reply_to_screen_name", replyToScreenname));
        }
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        String content = "";
        String id = "";
        StringBuilder builder = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            builder.append(line);
        }
        try {
            // there is only going to be one thing returned ever
            JSONObject jsonObject = new JSONObject(builder.toString());
            content = jsonObject.getString("tweet_content");
            id = jsonObject.getString("id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("talon_twitlonger", "content: " + content);
        Log.v("talon_twitlonger", "id: " + id);
        return new TwitLongerStatus(content, id);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) JSONObject(org.json.JSONObject) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BufferedReader(java.io.BufferedReader)

Example 69 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project dhis2-core by dhis2.

the class HttpUtils method httpPOST.

/**
     * <pre>
     * <b>Description : </b>
     * Method to make an http POST call to a given URL with/without authentication.
     *
     * @param requestURL
     * @param body
     * @param authorize
     * @param username
     * @param password
     * @param contentType
     * @param timeout
     * @return </pre>
     */
public static DhisHttpResponse httpPOST(String requestURL, Object body, boolean authorize, String username, String password, String contentType, int timeout) throws Exception {
    DefaultHttpClient httpclient = null;
    HttpParams params = new BasicHttpParams();
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    DhisHttpResponse dhisHttpResponse = null;
    try {
        HttpConnectionParams.setConnectionTimeout(params, timeout);
        HttpConnectionParams.setSoTimeout(params, timeout);
        httpclient = new DefaultHttpClient(params);
        HttpPost httpPost = new HttpPost(requestURL);
        if (body instanceof Map) {
            @SuppressWarnings("unchecked") Map<String, String> parameters = (Map<String, String>) body;
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                if (parameter.getValue() != null) {
                    pairs.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue()));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
        } else if (body instanceof String) {
            httpPost.setEntity(new StringEntity((String) body));
        }
        if (!StringUtils.isNotEmpty(contentType))
            httpPost.setHeader("Content-Type", contentType);
        if (authorize) {
            httpPost.setHeader("Authorization", CodecUtils.getBasicAuthString(username, password));
        }
        HttpResponse response = httpclient.execute(httpPost);
        log.info("Successfully got response from http POST.");
        dhisHttpResponse = processResponse(requestURL, username, response);
    } catch (Exception e) {
        log.error("Exception occurred in httpPOST call with username " + username, e);
        throw e;
    } finally {
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }
    return dhisHttpResponse;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicHttpParams(org.apache.http.params.BasicHttpParams) Map(java.util.Map)

Example 70 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project xmall by Exrick.

the class HttpUtil method sendPost.

/**
 * 发送HttpPost请求,参数为map
 * @param url 请求地址
 * @param map 请求参数
 * @return 返回字符串
 */
public static String sendPost(String url, Map<String, String> map) {
    // 设置参数
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    // 编码
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
    // 取得HttpPost对象
    HttpPost httpPost = new HttpPost(url);
    // 防止被当成攻击添加的
    httpPost.setHeader("User-Agent", userAgent);
    // 参数放入Entity
    httpPost.setEntity(formEntity);
    CloseableHttpResponse response = null;
    String result = null;
    try {
        // 执行post请求
        response = httpclient.execute(httpPost);
        // 得到entity
        HttpEntity entity = response.getEntity();
        // 得到字符串
        result = EntityUtils.toString(entity);
    } catch (IOException e) {
        log.error(e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }
    return result;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) 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) Map(java.util.Map)

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