Search in sources :

Example 31 with BasicResponseHandler

use of org.apache.http.impl.client.BasicResponseHandler in project android-sms-relay by nyaruka.

the class RelayService method sendAlert.

/**
	 * Sends an alert to our server with the passed in subject.  The body will contain
	 * configuration attributes and debugging information.
	 * 
	 * TODO: Would be nice to echo these out to SMS if the client is configured 
	 *       with an alert phone number.
	 *       
	 * @param subject The subject of the alert to send to the server
	 */
public static boolean sendAlert(Context context, String subject, String body) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String hostname = prefs.getString("router_hostname", null);
    Log.d(TAG, "__SENDING ALERT: " + subject);
    if (hostname != null && subject != null) {
        // send the alert off
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter("http.connection-manager.timeout", new Integer(60000));
        client.getParams().setParameter("http.connection.timeout", new Integer(60000));
        client.getParams().setParameter("http.socket.timeout", new Integer(60000));
        StringBuilder conf = new StringBuilder();
        conf.append("SMS Relay Version: " + AndroidRelay.getVersionNumber(context));
        conf.append("\n");
        conf.append("\nHostname: " + prefs.getString("router_hostname", null));
        String backend = prefs.getString("router_backend", null);
        conf.append("\nBackend:" + backend);
        conf.append("\nPassword:" + prefs.getString("router_password", null));
        conf.append("\n");
        conf.append("\nProcess Incoming:" + prefs.getBoolean("process_incoming", false));
        conf.append("\nProcess Outgoing:" + prefs.getBoolean("process_outgoing", false));
        conf.append("\nInterval:" + prefs.getString("update_interval", "null"));
        TextMessageHelper helper = AndroidRelay.getHelper(context);
        int total = helper.getAllMessages().size();
        int unsynced = helper.withStatus(context, TextMessage.INCOMING, TextMessage.RECEIVED).size();
        conf.append("\n");
        conf.append("\nTotal Messages:" + total);
        conf.append("\nUnsynced:" + unsynced);
        List<TextMessage> erroredOut = helper.withStatus(context, TextMessage.OUTGOING, TextMessage.ERRORED);
        conf.append("\n\nErrored Out: " + erroredOut.size());
        for (TextMessage msg : erroredOut) {
            conf.append("\n" + msg.number + ": " + msg.text);
        }
        List<TextMessage> erroredIn = helper.withStatus(context, TextMessage.INCOMING, TextMessage.ERRORED);
        conf.append("\n\nErrored In: " + erroredIn.size());
        for (TextMessage msg : erroredIn) {
            conf.append("\n" + msg.number + ": " + msg.text);
        }
        conf.append("\n\nLog:\n\n");
        // prepend our configuration to our body
        body = conf.toString() + body;
        try {
            HttpPost post = new HttpPost("http://" + hostname + "/router/alert");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("password", "" + prefs.getString("router_password", null)));
            nameValuePairs.add(new BasicNameValuePair("subject", "[" + backend + "] " + subject));
            nameValuePairs.add(new BasicNameValuePair("body", body));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            Log.e(MainActivity.TAG, "Sending log to: " + post.getURI().toURL().toString());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            client.execute(post, responseHandler);
            return true;
        } catch (Throwable t) {
            Log.e(MainActivity.TAG, "Sending of alert failed", t);
            return false;
        }
    }
    return false;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) SharedPreferences(android.content.SharedPreferences) ArrayList(java.util.ArrayList) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) TextMessage(com.nyaruka.androidrelay.data.TextMessage) TextMessageHelper(com.nyaruka.androidrelay.data.TextMessageHelper)

Example 32 with BasicResponseHandler

use of org.apache.http.impl.client.BasicResponseHandler in project android-sms-relay by nyaruka.

the class RelayService method fetchURL.

public String fetchURL(String url) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter("http.connection-manager.timeout", new Integer(25000));
    client.getParams().setParameter("http.connection.timeout", new Integer(25000));
    client.getParams().setParameter("http.socket.timeout", new Integer(25000));
    HttpGet httpget = new HttpGet(url);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String content = client.execute(httpget, responseHandler);
    return content;
}
Also used : DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 33 with BasicResponseHandler

use of org.apache.http.impl.client.BasicResponseHandler in project Asqatasun by Asqatasun.

the class DownloaderImpl method download.

private String download(String url) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    httpclient.getParams().setParameter("http.socket.timeout", Integer.valueOf(10000));
    httpclient.getParams().setParameter("http.connection.timeout", Integer.valueOf(10000));
    // Create a response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody;
    try {
        responseBody = httpclient.execute(httpget, responseHandler);
    } catch (HttpResponseException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (UnknownHostException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (SSLPeerUnverifiedException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (IOException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    }
    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
    return responseBody;
}
Also used : UnknownHostException(java.net.UnknownHostException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 34 with BasicResponseHandler

use of org.apache.http.impl.client.BasicResponseHandler in project cloudstack by apache.

the class PaloAltoResource method request.

/*
     * XML API commands
     */
/* Function to make calls to the Palo Alto API. */
/* All API calls will end up going through this function. */
protected String request(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
    if (method != PaloAltoMethod.GET && method != PaloAltoMethod.POST) {
        throw new ExecutionException("Invalid http method used to access the Palo Alto API.");
    }
    String responseBody = "";
    String debug_msg = "Palo Alto Request\n";
    // a GET method...
    if (method == PaloAltoMethod.GET) {
        String queryString = "?";
        for (String key : params.keySet()) {
            if (!queryString.equals("?")) {
                queryString = queryString + "&";
            }
            try {
                queryString = queryString + key + "=" + URLEncoder.encode(params.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new ExecutionException(e.getMessage());
            }
        }
        if (_key != null) {
            queryString = queryString + "&key=" + _key;
        }
        try {
            debug_msg = debug_msg + "GET request: https://" + _ip + s_apiUri + URLDecoder.decode(queryString, "UTF-8") + "\n";
        } catch (UnsupportedEncodingException e) {
            debug_msg = debug_msg + "GET request: https://" + _ip + s_apiUri + queryString + "\n";
        }
        HttpGet get_request = new HttpGet("https://" + _ip + s_apiUri + queryString);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            responseBody = s_httpclient.execute(get_request, responseHandler);
        } catch (IOException e) {
            throw new ExecutionException(e.getMessage());
        }
    }
    // a POST method...
    if (method == PaloAltoMethod.POST) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
        if (_key != null) {
            nvps.add(new BasicNameValuePair("key", _key));
        }
        debug_msg = debug_msg + "POST request: https://" + _ip + s_apiUri + "\n";
        for (NameValuePair nvp : nvps) {
            debug_msg = debug_msg + "param: " + nvp.getName() + ", " + nvp.getValue() + "\n";
        }
        HttpPost post_request = new HttpPost("https://" + _ip + s_apiUri);
        try {
            post_request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            throw new ExecutionException(e.getMessage());
        }
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            responseBody = s_httpclient.execute(post_request, responseHandler);
        } catch (IOException e) {
            throw new ExecutionException(e.getMessage());
        }
    }
    debug_msg = debug_msg + prettyFormat(responseBody);
    // test cases
    debug_msg = debug_msg + "\n" + responseBody.replace("\"", "\\\"") + "\n\n";
    return responseBody;
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 35 with BasicResponseHandler

use of org.apache.http.impl.client.BasicResponseHandler in project cloudstack by apache.

the class SspClient method executeMethod.

private String executeMethod(HttpRequestBase req, String path) {
    try {
        URI base = new URI(apiUrl);
        req.setURI(new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), path, null, null));
    } catch (URISyntaxException e) {
        s_logger.error("invalid API URL " + apiUrl + " path " + path, e);
        return null;
    }
    try {
        String content = null;
        try {
            content = getHttpClient().execute(req, new BasicResponseHandler());
            s_logger.info("ssp api call: " + req);
        } catch (HttpResponseException e) {
            s_logger.info("ssp api call failed: " + req, e);
            if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED && login()) {
                req.reset();
                content = getHttpClient().execute(req, new BasicResponseHandler());
                s_logger.info("ssp api retry call: " + req);
            }
        }
        return content;
    } catch (ClientProtocolException e) {
        // includes HttpResponseException
        s_logger.error("ssp api call failed: " + req, e);
    } catch (IOException e) {
        s_logger.error("ssp api call failed: " + req, e);
    }
    return null;
}
Also used : BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Aggregations

BasicResponseHandler (org.apache.http.impl.client.BasicResponseHandler)40 HttpGet (org.apache.http.client.methods.HttpGet)27 Test (org.junit.Test)15 IOException (java.io.IOException)11 HttpPost (org.apache.http.client.methods.HttpPost)10 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)8 ArrayList (java.util.ArrayList)7 HttpClient (org.apache.http.client.HttpClient)7 NameValuePair (org.apache.http.NameValuePair)6 ClientProtocolException (org.apache.http.client.ClientProtocolException)6 HttpResponseException (org.apache.http.client.HttpResponseException)6 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)6 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)6 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)6 RequestConfig (org.apache.http.client.config.RequestConfig)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)4 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2