HTTPのWebリクエストを送信しているときに私のアプリは、(強制停止)作業を停止しました

モハマド・ラジャビ:

このアプリケーションでは、私は、アプリがwork.Youに始まりながら、Webリクエストを送信したいここに私のコードを下に見ることができます:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    geturl("https://www.google.com/");
}
// and my other codes...

私は自分のWebリクエストを送信するには、この関数を使用します。

    public void geturl(String URL){
    HttpURLConnection client = null;
    try{
        URL url = new URL(URL);
        client = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(client.getInputStream());
        Toast.makeText(this, in.toString(), Toast.LENGTH_SHORT).show();
    } catch (MalformedURLException e) {
        //bad  URL, tell the user
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        //network error/ tell the user
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    } finally  {
        client.disconnect();
    }
}

あなたは私の見ることができますAndroidManifest.xmlダウンをここに:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.up.applications">
    <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>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

そしてまた、これは私のGradleです。

    apply plugin: 'com.android.application'
    android {
    compileSdkVersion 28
    defaultConfig {
    applicationId "coin.up.ozvdarozv"
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-  rules.pro'
        }
    }
}
    dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'org.apache.httpcomponents:httpcore:4.4.1'
    implementation("com.squareup.okhttp:okhttp:2.7.2")
    implementation 'com.android.volley:volley:1.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    }
    android {
    useLibrary 'org.apache.http.legacy'
    }

私は私のアプリを起動すると、それは私に強制停止異常を示し、私は私のアプリでエラーや問題を理解するために、任意のトーストのメッセージを参照してくださいいけません。

mubin986:

あなたは別のスレッドでURLを取得する必要があります。
使用しAsyncTask、バックグラウンドでURLを取得します。

  • あなたの同じアクティビティクラスでこのクラスを置きます:
private final class FetchUrl extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String response = "N/A"
        HttpURLConnection client = null;
        try{
            URL url = new URL("https://www.google.com/");
            client = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(client.getInputStream());
            response = in.toString();
        } catch (MalformedURLException e) {

        } catch (IOException e) {

        } finally  {
            client.disconnect();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {
        // Here, 'result' is the response of "https://www.google.com/".
        // Update your UI here.
    }
}
  • 活動のonCreate方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   new FetchUrl().execute();
}

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=385561&siteId=1