Daniel Rüscher Daniel Rüscher - 2 months ago 10
Android Question

call a link with an Android app

I want to call a link using a button for switching on and off a led

turns my led on:

http://10.0.0.3/light4on

turns my led off:

http://10.0.0.3/light4off

public void onClick(View v){

String link = "http://10.0.0.3/light4off";
try {
URL u = new URL(link);
HttpURLConnection http = (HttpURLConnection)u.openConnection();
// http.connect();
ausgabe.setText("working");

} catch (Exception e)
{
ausgabe.setText("not working");
}

}


but this isnĀ“t working...

I also added this to the manifest:

Answer

You can call any api which you are calling as url in your android application using HttpUrlConnection or OkHttp

First of all, request a permission to access network, add following to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

Following AsyncTask will be used to call http get method api in seperate thread:

class RequestTask extends AsyncTask<String, String, String>{
    String server_response;

    @Override
    protected String doInBackground(String... uri) {
     URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(uri[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            int responseCode = urlConnection.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}


// Converting InputStream to String

private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }


To call this class you have to write:    new RequestTask ().execute("http://10.0.0.3/light4on");
Comments