【发布时间】:2020-08-10 19:04:21
【问题描述】:
我创建了一个小演示程序
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;
}
}
}
我在int responseCode = urlConnection.getResponseCode(); 处设置了一个断点,然后单步执行。它永远不会到达下一行让我阅读响应代码。没有错误;它只是永远挂起。
我觉得这是我能想到的最基本的 urlconnection 代码。也许我错过了一些重要的东西。
编辑:我确实在我的清单中添加了互联网权限。这是我的整个清单,以防万一:
<?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>
更新: 我已经编辑了我的代码以包括从请求中读取。
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;
}
}
}
当我在代码和演练的开头设置断点时,它冻结在InputStream in = new BufferedInputStream(urlConnection.getInputStream());
所以这并不能解决问题。
解决方案更新: 我正在使用的 android 模拟设备出了点问题。我重新启动它,现在问题已解决。如果您知道发生这种情况的原因,请让我和互联网上的其他人知道,这样我们就可以避免它!
【问题讨论】:
-
检查清单中是否包含互联网权限。
-
我已经添加了。事实上,我的应用一开始就崩溃了,因为我没有添加它,所以我必须先解决这个问题。
-
请添加更多错误日志
-
@McSlinPlay 不再有错误日志。我添加了互联网权限,所以没有错误。它只是冻结
-
即使您删除断点并实时执行代码?