Hit a URL without opening browser in Android Studio

我怕爱的太早我们不能终老 提交于 2019-12-12 05:48:10

问题


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);
        }
    });


来源:https://stackoverflow.com/questions/42294863/hit-a-url-without-opening-browser-in-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!