Execute a HTTP request within an app

2019-08-23 07:10发布

问题:

I was wondering if I could make it open But NOT open the android browser, I just need it to visit: (pretend this is the ip) http;//91.91.91.91:2228?1, where it will trigger action on my arduino mega. I have tried to get it just to do this with this code

onclick(Intent websiteIntent = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.parse("http;//91.9.91.91:?1");
    websiteIntent.setData(uri);
    startActivity(websiteIntent);)

but I don't know how to get it to do so

回答1:

A HttpClient will allow you to call an arbitrary URL within your app:

DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http;//91.9.91.91:?1");
HttpResponse response = client.execute(request);

Don't forget to wrap in a try catch though.

edit:

new Thread(){
    public void run(){
        try{
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http;//91.9.91.91:?1");
            HttpResponse response = client.execute(request);
        }catch(Exception e){
            // Handle the exception
            e.printStackTrace();
        }
    }
};