Hit a URL without opening browser in Android Studi

2019-09-14 21:07发布

问题:

i have looked at many places, tried a ton of things but nothing to seem to work for me somehow. Can anyone please help me here. I have a simple url that i want to hit without opening the browser in mobile phones. I am clicking a button and that url needs to get hit, without the browser getting opened. I am not concerned with what is on that page i just want to load it. I basically need it for my arduino cum ethernet shield IOT project, wherein i am controlling my appliances with my android phone.

Here is a snippet of what i am doing. The apk is generating without errors but the url is not getting hit somehow.

Thankyou

public void led1on(View view){
      try {
        URL u = new URL("http://172.17.27.173/?2");
        HttpURLConnection http = (HttpURLConnection) u.openConnection();
        http.connect();
    }catch (Exception e){
        e.getMessage();
        e.printStackTrace();
    }
}

回答1:

You can call it as a web service and do nothing with the results. For example:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://172.17.27.173/yourpage", params, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) { // 200 OK
        // Do nothing
    }
    @Override
    public void onFailure(int statusCode, Throwable error, String content) { // Response not 200
    {
        // Some troubleshooting, etc.
    }
});

In order to see how to use the above code, you can take a look at here which has explained how to use the code for Android: http://loopj.com/android-async-http/

It is also possible to use some other library such as Apache Http client as well: https://hc.apache.org/

try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        myContent = httpEntity.getContent();

    } catch ...


回答2:

Use this method to open url with in your application

You can call this url like your api calling, it calls url without any display. Or make an api(web service) and hit from the application and at api end call your url.



回答3:

It can be done in following simplest way.

switchON.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String webID = "Your url to turn ON device";
            Intent bIntent = new Intent();
            bIntent.setAction(Intent.ACTION_VIEW);
            bIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            bIntent.setData(Uri.parse(webID));
            startActivity(bIntent);
        }
    });