The method sendMessage(View view)
runs on clicking a button. The method is being called successfully because t.setText("Checking...");
changes the text to Checking...
as expected.
The issue is that the app force closes when s= urlConnection.getResponseCode();
is not commented out. Is it because a connection is not being established or have I missed out something in code?
I am new to android programming and couldn't find a proper guide or video tutorial on web services using HttpUrlConnection. I would like to learn this before moving on to REST, SOAP or other APIs.
What have I tried?
Changed URL to a sub-domain I own but it still crashes.
Searched on forums and StackOverflow and came across something called AsyncTask. I am not sure if that's necessary here because I didn't find that as a requirement in Android Doc. I learnt most of the connection part from Android Doc since video tutorials didn't explain well.
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void sendMessage(View view) throws IOException {
TextView t=findViewById(R.id.hello2);
t.setText("Checking...");
URL url = new URL("http://google.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
int s=0;
s= urlConnection.getResponseCode();
t.setText("Nice.");
} finally {
urlConnection.disconnect();
}
}
}
I am aware that things get easier with APIs like REST and SOAP but I would like to do it this way for learning purposes. It would be awesome if someone could guide me to a proper tutorial or blog about the same. I honestly couldn't find anything properly explained in the tutorials I referred.