0

I created a small demo program

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        (new Requester()).execute();
    }

    static class Requester extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... voids) {
            URL loginURL;
            HttpURLConnection urlConnection;
            try {
                loginURL = new URL("https://google.com");
                urlConnection = (HttpURLConnection) loginURL.openConnection();

                int responseCode = urlConnection.getResponseCode();
                Log.d("response", "response is" + responseCode);
            }
            catch (MalformedURLException e){
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            return null;
        }
    }
}

I set a breakpoint at int responseCode = urlConnection.getResponseCode(); and then step through. It never gets to the next line for me to read the response code. There is no error; it just hangs forever.

I feel like this is the most basic urlconnection code I can come up with. Perhaps I'm missing something important.

Edit: I have indeed added the internet permission to my manifest. Here is my entire manifest just in case you want it:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testingcorruptbitmap">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Update: I've edited my code to include reading from the request.

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        (new Requester()).execute();
    }

    static class Requester extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... voids) {
            URL loginURL;
            HttpURLConnection urlConnection;
            try {
                loginURL = new URL("https://google.com");
                urlConnection = (HttpURLConnection) loginURL.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line = reader.readLine();
                Log.d("urlconnection", "line is " + line);
                int responseCode = urlConnection.getResponseCode();
                Log.d("urlconnection", "response is " + responseCode);
            }
            catch (MalformedURLException e){
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
    }
}

When I set a breakpoint at the beginning of the code and walkthrough, it freezes at InputStream in = new BufferedInputStream(urlConnection.getInputStream()); So this does not solve the issue.

Solution update: Something was wrong with the android emulated device I was working on. I restarted it and the problem is now fixed. If you know of the reason why this would happen please let me and the rest of the internet know, so we can avoid it!

Malachi Holden
  • 275
  • 1
  • 12

3 Answers3

0

have you added the INTERNET permission in your AndroidManifest? If not do so. If you did take a look at this document by android-dev. It shows how to make simple requests using the volley library.

Hope this helps

Edit: I personally never worked with URLConnection but according to the android docs you have to do it like this:

   URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

Source: https://developer.android.com/reference/java/net/HttpURLConnection

In your example you just created a HttpURLConnection but never executed it and thats why you can'T get something of it.

While it can definitly work this this method I would greatly encurage you to take a look at Volley as it is more simple and easier to use. It also helps you with JSONRequests. Furthermore it is async by default meaning you don't need to use the deprecated AsyncTask anymore.

Edit 2: When trying to connect to a secure website over https as you try to do in your example you need to cast to HttpsURLConnection instead.

McSlinPlay
  • 449
  • 2
  • 13
  • See my update to the original question for the internet permission question. As for Volley -- I don't intend to completely rewrite my app to use a different tool, sorry. Do you know about how to avoid my issue with just UrlConnection? I figured UrlConnection should have the basic functionality even if it doesn't do what volley does – Malachi Holden Aug 11 '20 at 02:42
  • See my latest update. Reading from the request does not help – Malachi Holden Aug 11 '20 at 13:04
  • I changed to using HttpsUrlConnection and it still freezes. I can post the updated code if you want – Malachi Holden Aug 11 '20 at 15:14
0

You are not doing an actual request, so there is no response either, that's why your code is waiting for a response.

See here: Http Get using Android HttpURLConnection

Ridcully
  • 23,362
  • 7
  • 71
  • 86
0

I also have the same problem, the call to the getResponseCode method freezes. If I set a timeout, the timeout expired exception is thrown. But all of the above happens when I have the phone in power saving mode, if I remove it, the call to the getResponseCode method works perfectly.

If the Volley api is used, a timeout also occurs.

But this only happens in background processes for example when updating a widget due to restrictions imposed by the system.

The solution is to add your app to the list of energy saving exclusions. Although this can be done through the PowerManager api, it is preferable that it be the user of your app who does it, as discussed in this answer https://stackoverflow.com/a/53115804/1735246.

Caeiro
  • 1
  • 3