Android: API with HttpURLConnection: android.os.NetworkOnMai



我想创建Android meteo应用程序。因此,我使用Web API通过HttpURLConnection方法获取天气:

package com.example.monlouis.myapplication;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherAPI {
/*
    Liste des informations utiles à récupérer :
    Température actuelle Kelvin : main->temp
    Température min Kelvin : main->temp_min
    Température max Kelvin : main->temp_max
    Humidité actuelle : main->humidity
    Coordonnées GPS (longitude) : coord->lon
    Coordonnées GPS (latitude) : coord->lat
    Nom de la ville : name
    Pays : sys->country
    Description courte du temps : weather->0->main
    Description longue du temps : weather->0->description
*/
private static String API_URL = "http://api.openweathermap.org/data/2.5/weather";
private static String API_KEY = "b1b15e88fa797225412429c1c50c122a1";
// Recherche de la météo par code postal + code du pays (fr, en...)
public String getWeatherByZipCode(String zipCode, String countryCode) {
    HttpURLConnection con = null;
    InputStream is = null;
    try {
        con = (HttpURLConnection) ( new URL(API_URL + "?zip=" + zipCode + "," + countryCode + "&appid=" + API_KEY)).openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();
        StringBuffer buffer = new StringBuffer();
        is = con.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while( (line = br.readLine()) != null) {
            buffer.append(line + "rn");
        }
        is.close();
        con.disconnect();
        return buffer.toString();
    }
    catch(Throwable t) {
        t.printStackTrace();
    }
    finally {
        try { is.close(); } catch(Throwable t) {}
        try { con.disconnect(); } catch(Throwable t) {}
    }
    return null;
}
// Recherche de la météo par nom de la ville + code du pays (fr, en...)
public static String getWeatherByCityName(String cityName, String countryCode) {
    HttpURLConnection con = null;
    InputStream is = null;
    try {
        System.out.println(cityName);
        System.out.println(countryCode);
        con = (HttpURLConnection) ( new URL(API_URL + "?q=" + cityName + "," + countryCode + "&appid=" + API_KEY)).openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();
        StringBuffer buffer = new StringBuffer();
        is = con.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while( (line = br.readLine()) != null) {
            buffer.append(line + "rn");
        }
        is.close();
        con.disconnect();
        return buffer.toString();
    }
    catch(Throwable t) {
        t.printStackTrace();
    }
    finally {
        try { is.close(); } catch(Throwable t) {}
        try { con.disconnect(); } catch(Throwable t) {}
    }
    return null;
}
// Recherche de la météo par coordonées GPS
public String getWeatherByCoord(double lat, double lon) {
    HttpURLConnection con = null;
    InputStream is = null;
    try {
        con = (HttpURLConnection) ( new URL(API_URL + "?lat=" + String.valueOf(lat) + "&lon=" + String.valueOf(lon) + "&appid=" + API_KEY)).openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();
        StringBuffer buffer = new StringBuffer();
        is = con.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while( (line = br.readLine()) != null) {
            buffer.append(line + "rn");
        }
        is.close();
        con.disconnect();
        return buffer.toString();
    }
    catch(Throwable t) {
        t.printStackTrace();
    }
    finally {
        try { is.close(); } catch(Throwable t) {}
        try { con.disconnect(); } catch(Throwable t) {}
    }
    return null;
}
}

而且,我在 MainActivity 上调用我的 API:

package com.example.monlouis.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText mContenuText;
Button valider;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button bouton = (Button) findViewById(R.id.ValideButton);
    valider = (Button) findViewById(R.id.ValideButton);
    mContenuText = (EditText)findViewById(R.id.editText);
    valider.setOnClickListener(this);
    //System.out.println(strDate);
}

public void onClick(View v)
{
    // TODO Auto-generated method stub
    String chaine = mContenuText.getText().toString();
    Log.v("Essai",chaine);
    String infoAPI = WeatherAPI.getWeatherByCityName(chaine, "fr");
    System.out.println(infoAPI);
    ((TextView)findViewById(R.id.textView3)).setText("Ville: " + chaine);
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMMM/d/E", Locale.FRANCE); // Set your locale!
    String strDate = sdf.format(cal.getTime());
    System.out.println(strDate);
}
}

我在 AndroidManifest 中添加权限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.monlouis.myapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    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>

但是当我想在我的智能手机(控制台(上执行应用程序时,我遇到了此错误:

03-18 15:07:14.093 27210-27210/com.example.monlouis.myapplication I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-18 15:07:14.093 27210-27210/com.example.monlouis.myapplication I/System.out: (HTTPLog)-Static: isShipBuild true
03-18 15:07:14.093 27210-27210/com.example.monlouis.myapplication I/System.out: (HTTPLog)-Thread-1-982556185: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
03-18 15:07:14.093 27210-27210/com.example.monlouis.myapplication I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-18 15:07:14.103 27210-27210/com.example.monlouis.myapplication W/System.err: android.os.NetworkOnMainThreadException
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:367)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:295)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.example.monlouis.myapplication.WeatherAPI.getWeatherByCityName(WeatherAPI.java:75)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.example.monlouis.myapplication.MainActivity.onClick(MainActivity.java:46)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at android.view.View.performClick(View.java:5197)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at android.view.View$PerformClick.run(View.java:20926)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:145)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5951)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
03-18 15:07:14.113 27210-27210/com.example.monlouis.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

为什么?你能帮我吗?

谢谢!

您需要在

UI 线程中调用 WeatherAPI 类中的所有方法...这是为了确保您不会阻止 UI 线程(导致 UI 挂起或阻止用户(。

Android 中内置了几种不同的功能来处理这些事情......查看AsyncTasks或IntentServices。

常规文档:https://developer.android.com/guide/components/processes-and-threads.html

永远不要调用主线程上的网络操作使用加载器或异步任务,这些数据密集型操作需要后台线程处理。

最新更新