Example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler.

Prototype

BasicResponseHandler

Source Link

Usage

From source file:com.jive.myco.seyren.core.service.notification.SlackNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String token = seyrenConfig.getSlackToken();
    String channel = subscription.getTarget();
    String username = seyrenConfig.getSlackUsername();
    String iconUrl = seyrenConfig.getSlackIconUrl();

    List<String> emojis = Lists.newArrayList(
            Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getSlackEmojis()));

    String url = String.format("%s/api/chat.postMessage", baseUrl);
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    post.addHeader("accept", "application/json");

    List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    parameters.add(new BasicNameValuePair("token", token));
    parameters.add(new BasicNameValuePair("channel", channel));
    parameters.add(new BasicNameValuePair("text", formatContent(emojis, check, subscription, alerts)));
    parameters.add(new BasicNameValuePair("username", username));
    parameters.add(new BasicNameValuePair("icon_url", iconUrl));

    try {/*from w w  w.ja va  2s  .c  o  m*/
        post.setEntity(new UrlEncodedFormEntity(parameters));
        HttpResponse response = client.execute(post);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Status: {}, Body: {}", response.getStatusLine(),
                    new BasicResponseHandler().handleResponse(response));
        }
    } catch (Exception e) {
        LOGGER.warn("Error posting to Slack", e);
    } finally {
        post.releaseConnection();
        HttpClientUtils.closeQuietly(client);
    }

}

From source file:org.qi4j.library.shiro.StrictX509Test.java

@Test
public void test() throws IOException {
    HttpGet get = new HttpGet(SECURED_SERVLET_PATH);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    DefaultHttpClient client = new DefaultHttpClient();
    SSLSocketFactory sslsf = new SSLSocketFactory(X509FixturesData.clientSSLContext());
    sslsf.setHostnameVerifier(new AllowAllHostnameVerifier()); // For unit testing convenience only, do not use in production
    Scheme https = new Scheme("https", sslsf, httpHost.getPort());
    client.getConnectionManager().getSchemeRegistry().register(https);

    String response = client.execute(httpHost, get, responseHandler);
    assertEquals(ServletUsingSecuredService.OK, response);
}

From source file:com.weiboa.data.WeiboOAuthConnect.java

private JSONObject sendGetRequest(HttpGet get) {
    JSONObject jso = null;/*from  ww w.j  a v a 2 s  .  c o m*/
    boolean ok = false;
    try {
        mConsumer.sign(get);
        String response = mClient.execute(get, new BasicResponseHandler());
        jso = new JSONObject(response);
        Log.d(TAG, "authenticatedQuery: " + jso.toString(2));
        ok = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (!ok) {
        jso = null;
    }
    return jso;
}

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

@Test
public void testWebSocketMsg()
        throws IOException, InterruptedException, ExecutionException, DeploymentException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    final HttpGet httpGet = new HttpGet("http://localhost:8080");
    HttpClients.custom().setDefaultRequestConfig(requestConfig).setDefaultCookieStore(cookieStore).build()
            .execute(httpGet, new BasicResponseHandler());

    final SettableFuture<String> res = new SettableFuture<>();
    final WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    wsContainer.setAsyncSendTimeout(timeout);
    wsContainer.setDefaultMaxSessionIdleTimeout(timeout);
    try (final Session ignored = wsContainer.connectToServer(sendAndGetTextEndPoint("test it", res),
            getClientEndPointConfig(cookieStore), URI.create("ws://localhost:8080/ws"))) {
        final String s = res.get();
        assertEquals("test it", s);
    }/*from w w w . j  ava 2s .co  m*/
}

From source file:com.da.img.BoradList.java

protected void executeURL(String p_page) throws IOException, ClientProtocolException, URISyntaxException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from   ww w.j  ava  2  s. co m*/
        HttpGet httpget = executeLogin(httpclient);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = "";
        // /bank/story_mn.php?p_userid=bluesman&p_snum=201&p_num=35788
        // String strUrl = "http://story.soraspace.info/bank/story_mn.php?p_userid=bluesman&p_snum=201&p_num=35821";
        //  : http://photo.soraspace.info/album/theme/pic_list.php?p_anum=173&p_ix=3&p_gnum=351
        // http://photo.soraspace.info/album/theme/pic_list.php?p_page=1&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt=
        // http://photo.soraspace.info/album/theme/pic_list.php?p_page=2&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt=
        // http://photo.soraspace.info/album/theme/pic_list.php?p_page=3&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt=
        // http://photo.soraspace.info/album/theme/pic_list.php?p_page=3&p_sort=D&p_anum=351&p_gnum=351&p_soption=&p_stxt=

        String imgUrl;
        // 351 : mom , 481: lip
        String SaveFilePath = "c:/temp/173";
        String p_gnum = "351";
        List<ImageVo> lst = null;
        int max_page = 10000;
        String output = "";
        InputStream istream;
        int init_page = 1;
        if (!"".equals(StringUtils.stripToEmpty(p_page))) {
            init_page = Integer.parseInt(p_page);
        }
        for (int i = init_page; i < max_page; i++) {
            lst = getBoardList(httpclient, httpget, responseHandler, p_gnum, String.valueOf(i));
            for (ImageVo vo : lst) {
                // continue;
                imgUrl = vo.getImgUrl(); //"http://photo2.soraspace.info/thumbnail.php?p_imgwidth=1104&p_imgheight=1104&p_width=1104&p_height=1104&p_imgfile=%2F%2F201205%2F22%2Fsk650%2F%2F1501694.jpg&verify=%2F%90%F9%B7%D6%D0%12%0EF%17%B8M%DA%A4L%C4";
                istream = getDownloadUrlInputStream(httpclient, httpget, imgUrl);
                // System.out.println("result = " + istream.toString());
                output = SaveFilePath + "/" + p_gnum + "/"
                        + org.apache.commons.lang.StringUtils.leftPad(String.valueOf(i), 4, "0") + "/"
                        + vo.getFileName();
                fileDownCopy(output, istream);
                if (istream != null) {
                    istream.close();
                }
            }
        }

    } catch (Exception ex) {
        System.out.println("ERROR: " + ex.getLocalizedMessage());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.da.img.BoradHipList.java

protected void executeURL(String p_page) throws IOException, ClientProtocolException, URISyntaxException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from   w  w  w  .j  a v a  2  s .c  o m
        HttpGet httpget = executeLogin(httpclient);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = "";
        // /bank/story_mn.php?p_userid=bluesman&p_snum=201&p_num=35788
        // String strUrl =
        // "http://story.soraspace.info/bank/story_mn.php?p_userid=bluesman&p_snum=201&p_num=35821";
        //  :
        // http://photo.soraspace.info/album/theme/pic_list.php?p_anum=173&p_ix=3&p_gnum=351
        // http://photo.soraspace.info/album/theme/pic_list.php?p_page=1&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt=
        // http://photo.soraspace.info/album/theme/pic_list.php?p_page=2&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt=
        // http://photo.soraspace.info/album/theme/pic_list.php?p_page=3&p_sort=D&p_anum=173&p_gnum=351&p_soption=&p_stxt=
        // http://photo.soraspace.info/album/theme/pic_list.php?p_page=3&p_sort=D&p_anum=351&p_gnum=351&p_soption=&p_stxt=

        String imgUrl;
        // p_anum=244&p_ix=1 ? 
        // p_anum=281&p_ix=2 
        // p_anum=173&p_ix=3 ?
        // p_gnum= 351 : mom , 481: lip , 352: hip,
        // 354:ga,353:leg,442:pussy,
        String SaveFilePath = "c:/temp/173";
        String p_gnum = "352";
        List<ImageVo> lst = null;
        int max_page = 10000;
        String output = "";
        InputStream istream;
        int init_page = 1;
        if (!"".equals(StringUtils.stripToEmpty(p_page))) {
            init_page = Integer.parseInt(p_page);
        }
        for (int i = init_page; i < max_page; i++) {
            lst = getBoardList(httpclient, httpget, responseHandler, p_gnum, String.valueOf(i));
            for (ImageVo vo : lst) {
                // continue;
                imgUrl = vo.getImgUrl(); // "http://photo2.soraspace.info/thumbnail.php?p_imgwidth=1104&p_imgheight=1104&p_width=1104&p_height=1104&p_imgfile=%2F%2F201205%2F22%2Fsk650%2F%2F1501694.jpg&verify=%2F%90%F9%B7%D6%D0%12%0EF%17%B8M%DA%A4L%C4";
                istream = getDownloadUrlInputStream(httpclient, httpget, imgUrl);
                // System.out.println("result = " + istream.toString());
                output = SaveFilePath + "/" + p_gnum + "/"
                        + org.apache.commons.lang.StringUtils.leftPad(String.valueOf(i), 4, "0") + "/"
                        + vo.getFileName();
                fileDownCopy(output, istream);
                if (istream != null) {
                    istream.close();
                }
            }
        }

    } catch (Exception ex) {
        System.out.println("ERROR: " + ex.getLocalizedMessage());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:de.freegroup.twogo.plotter.rpc.Client.java

private String getToken(CloseableHttpClient httpclient) throws Exception {

    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
    HttpPost request = new HttpPost(this.serverUrl + "Echo");
    request.setConfig(config);//  w  w  w  .ja  v  a 2s. c  o  m
    request.setHeader("Content-Type", "text/plain");
    request.setHeader("X-CSRF-Token", "Fetch");

    try {

        JSONObject message = buildParam("echo", new String[] { "any" });

        StringEntity body = new StringEntity(message.toString(),
                ContentType.create("application/json", Consts.UTF_8));

        request.setEntity(body);
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());

        CloseableHttpResponse response = httpclient.execute(request);

        JSONTokener tokener = new JSONTokener(new BasicResponseHandler().handleResponse(response));
        Object rawResponseMessage = tokener.nextValue();
        JSONObject responseMessage = (JSONObject) rawResponseMessage;
        if (responseMessage == null) {
            throw new ClientError("Invalid response type - " + rawResponseMessage.getClass());
        }

        return (responseMessage.getJSONObject("result").getJSONObject("header").getString("value"));

    } catch (Exception e) {
        throw new ClientError(e);
    }
}

From source file:ca.sqlpower.enterprise.ServerInfoProvider.java

private static void init(URL url, String username, String password, CookieStore cookieStore)
        throws IOException {

    if (version.containsKey(generateServerKey(url, username, password)))
        return;/*from w ww.j ava  2 s. c  o m*/

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(cookieStore);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(url.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(url, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(url, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(url, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer || (watermarkMessage != null && watermarkMessage.trim().length() > 0)) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    HyperlinkListener hyperlinkListener = new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            try {
                                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                    if (e.getURL() != null) {
                                        BrowserUtil.launch(e.getURL().toString());
                                    }
                                }
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    };
                    HTMLUserPrompter htmlPrompter = new HTMLUserPrompter(UserPromptOptions.OK,
                            UserPromptResponse.OK, null, watermarkMessage, hyperlinkListener, "OK");
                    htmlPrompter.promptUser("");
                }
            });
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:de.perdian.apps.dashboard.support.clients.JsonClient.java

/**
 * Executes the given job and return the response
 *
 * @param requestUri//from  w  w  w  . j  a  v  a 2 s.  c  o m
 *     the URI to which the request should be sent
 * @return
 *     the JSON result
 */
public JsonNode sendRequest(CharSequence requestUri) {
    try {

        HttpGet httpGet = new HttpGet(requestUri.toString());
        if (this.getUsername() != null && this.getPassword() != null) {
            httpGet.addHeader(new BasicScheme().authenticate(
                    new UsernamePasswordCredentials(this.getUsername(), this.getPassword()), httpGet,
                    new BasicHttpContext()));
        }
        for (Map.Entry<Object, Object> defaultHeaderEntry : this.getDefaultHeaders().entrySet()) {
            httpGet.addHeader((String) defaultHeaderEntry.getKey(), (String) defaultHeaderEntry.getValue());
        }

        String httpResponseString = this.getHttpClient().execute(httpGet, new BasicResponseHandler());
        return JsonUtil.fromJsonString(httpResponseString);

    } catch (Exception e) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("Cannot send HTTP request [").append(requestUri);
        errorMessage.append("] using client [").append(this).append("]");
        log.debug(errorMessage.toString(), e);
        throw new DashboardException(errorMessage.toString(), e);
    }
}