Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No response from HTTP GET code when put in Android Activity

I'm trying to write an app that involves an activity that sends a GET request to a webpage, gets the code as a response and then parses it for one specific string (the winner's name). This works just fine when I run it as a stand-alone Java code on my terminal. Putting it into an Android activity though yields no results: neither success nor errors.

Given below is the code of the MainActivity:

package com.projects.appbrewers.swaghrwtracker;

package com.example.myprojects.myapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private final String USER_AGENT = "Mozilla/5.0";
    String url = "<some URL here>";
    String currentWinnerName = "";

    TextView currentWinnerLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);
        currentWinnerLabel.setText("Finding...");
        try
        {
            checkCurrentWinner();
        }
        catch (Exception e)
        {
            //print e.getMessage() to log
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //HTTP GET Request to Swagbucks HRW iframe page
    public void checkCurrentWinner() throws Exception
    {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();

        if(responseCode == 200)
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null)
            {
                response.append(inputLine);
            }
            in.close();

            // strip out your required data with a regex
            Pattern pattern = Pattern.compile(".*<div id=\"randomWinnerName\">([a-z0-9]*)</div>.*");
            Matcher matcher = pattern.matcher(response.toString());

            if (matcher.find())
            {
                currentWinnerName = matcher.group(1);
                currentWinnerLabel.setText(currentWinnerName);
            }
            else
                currentWinnerLabel.setText("Not Found!");
        }
        else
            currentWinnerLabel.setText("ERROR!");
    }
}
like image 509
Darth Coder Avatar asked Jun 22 '26 14:06

Darth Coder


1 Answers

Here are two options to do it: 1. Use an AsyncTask to perform the HTTP GET operation

private class CheckUsernameFromUrlTask extends AsyncTask<URL, Integer, String> {
     protected String doInBackground(URL... urlToGetTheUsername) {
         String usernameFromHttpGetMethod = null;
         // code to make (similar to your checkCurrentWinner method)
         //   1. HTTP GET request
         //   2. Extract username (incl. error handling)
         return usernameFromHttpGetMethod;
     }

     protected void onProgressUpdate(Integer... progress) {
         // ignore for now, unless you want to show the progress blocking UI
     }

     protected void onPostExecute(String result) {
         // back in the UI thread. Perform all view operations
         // Handle exceptions by saving the exception thrown in 
         // doInBackground method as an instance variable of this class or
         // changing the return object to be a custom object containing
         // username and exception.
         String labelText = result == null ? "Not Found!" : result;
         currentWinnerLabel.setText(labelText );
     }
 }

Then to use the AsyncTask

@Override
protected void onCreate(Bundle savedInstanceState) {
   // ...
   new CheckUsernameFromUrlTask ().execute(url1, url2, url3);
}
  1. Use the retrofit library. The library uses a Callback object to get the request asynchronously via a background thread, so you don't have to write code for an AsyncTask. See the documentation for retrofit for examples.
like image 75
Thira Avatar answered Jun 24 '26 04:06

Thira