HttpURLConnection connect()方法失败并崩溃

时间:2018-05-06 09:25:51

标签: android web-services android-studio httpurlconnection networkonmainthread

我试图通过以下代码调用Web服务。但httpUrlConnection.connect()失败,应用程序开始崩溃。

           try {
                URL serverAddress = new URL("http://thesaurus.altervista.org/thesaurus/v1?word=peace&language=en_US&key=code&output=json");

                HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
                connection.connect();

                int rc = connection.getResponseCode();
                if (rc == 200) {
                    String line = null;
                    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    while ((line = br.readLine()) != null)
                        sb.append(line + '\n');
                    JSONObject obj = (JSONObject) JSONValue.parse(sb.toString());
                    JSONArray array = (JSONArray)obj.get("response");
                    for (int i=0; i < array.size(); i++) {
                        JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
                        System.out.println(list.get("category")+":"+list.get("synonyms"));
                    }
                } else System.out.println("HTTP error:"+rc);
                connection.disconnect();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

logcat的

    05-06 13:08:55.951 1133-1546/? D/NetworkController.MobileSignalController(4): onSignalStrengthsChanged signalStrength=SignalStrength: 11 35 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 2147483647 gsm|lte 2147483647 -396 7 level=3
    updateTelephonySignalStrength: hasService=true ss=SignalStrength: 11 35 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 2147483647 gsm|lte 2147483647 -396 7
05-06 13:08:55.951 1133-1546/? D/jadon_level: dbm = -99        3G level = 3
05-06 13:08:55.951 1133-1546/? D/NetworkTypeUtils: getNetworkType: type=10
    getNetworkTypeIcon iconId = 2130838720
05-06 13:08:55.954 989-30195/? V/ActivityManager: Broadcast sticky: Intent { act=android.intent.action.SIG_STR flg=0x20000010 (has extras) } ordered=false userid=-1 callerApp=ProcessRecord{5d682d5 989:system/1000}
05-06 13:08:55.999 1133-1133/? D/NetworkController.WifiSignalController: Change in state from: connected=true,enabled=true,level=4,inetCondition=1,iconGroup=IconGroup(Wi-Fi Icons),activityIn=false,activityOut=false,rssi=-56,lastModified=05-06 01:08:55,ssid="SLT-ADSL-716FA"
        to: connected=true,enabled=true,level=4,inetCondition=1,iconGroup=IconGroup(Wi-Fi Icons),activityIn=true,activityOut=true,rssi=-56,lastModified=05-06 01:08:55,ssid="SLT-ADSL-716FA"
05-06 13:08:56.029 329-485/? D/AALService: enableAALEvent: 0 -> 1
05-06 13:08:56.033 329-485/? D/AALService: enableAALEvent: 1 -> 0
    05-06 01:08:56.029 BL= 542,CABC= 256, 
05-06 13:08:56.074 25164-25164/? D/dumpsys: dumpsys start
05-06 13:08:56.125 11433-11433/? D/WebView: evaluateJavascript=AFMA_updateActiveView({"units":[{"afmaVersion":"afma-sdk-a-v12529018.11020000.1","activeViewJSON":{"click_string":"BM1YBiHPsWvvZBdOmoAPAtK7IBgCd7P2n-wYAABABOAHIAQnIAwLgBAOIBc3mi4wFoAZM0ggFCIABEAE,BwsSviHPsWriuA4S9oAOvhIHQBJeF7ZxFAAAAEAEgx4v0SzgAWOf78PmCBGCRmewEsgE2MjIwMzM4LmFuZHJvaWQuY29tLnZpYmVyLnZvaXAuYWRzZW5zZWZvcm1vYmlsZWFwcHMuY29tugEJZ2ZwX2ltYWdlyAEJ2gE-aHR0cDovLzIyMDMzOC5hbmRyb2lkLmNvbS52aWJlci52b2lwLmFkc2Vuc2Vmb3Jtb2JpbGVhcHBzLmNvbS-YAsgBwAIC4AIA6gIfLzY1NjU2MjYzL3Rlc3QvVGltZV9PdXRfMzAweDI1MPgC_NEekAOaCJgD0AWoAwHIAwLgBAHSBQYQvdenqhGQBgGgBjvYBgLYBwDgBx_yBwIgAdIIBwiAARABGAE","is_active_view_immediate_enabled":true,"activeview_cpm_urls":[],"active_experiment_ids":"","activeview_cid":"CAASUeRosf6NHpD3haoD6Hs7FeKRN3UOiX3uvD2Rjlflkl6up87tCfD5lMj3A7hO1JNP3b6C_3ptfeOEU44zDYfwEBdpj3HGy18gKYjKinIQLOpoVw"},"timestamp":489872398,"adFormat":"300x250_as","hashCode":"0307fc59-3858-4be2-9ad6-f286cf9ed0ae","isMraid":true,"isStopped":false,"isPaused":false,"isNative":false,"isScreenOn":true,"appMuted":false,"appVolume":1,"deviceVolume":0.800000011920929,"windowVisibility":8,"isAttachedToWindow":false,"viewBox":{"top":0,"bottom":569,"left":0,"right":320},"adBox":{"top":0,"bottom":0,"left":0,"right":0},"globalVisibleBox":{"top":0,"bottom":0,"left":0,"right":0},"globalVisibleBoxVisible":false,"localVisibleBox":{"top":0,"bottom":0,"left":0,"right":0},"localVisibleBoxVisible":false,"hitBox":{"top":0,"bottom":0,"left":0,"right":0},"screenDensity":1.5,"isVisible":false}]});
05-06 13:08:56.126 11433-11433/? D/WebView: evaluateJavascript=AFMA_updateActiveView({"units":[{"afmaVersion":"afma-sdk-a-v12529018.11020000.1","activeViewJSON":{"click_string":"BM1YBiHPsWvvZBdOmoAPAtK7IBgCd7P2n-wYAABABOAHIAQnIAwLgBAOIBc3mi4wFoAZM0ggFCIABEAE,BwsSviHPsWriuA4S9oAOvhIHQBJeF7ZxFAAAAEAEgx4v0SzgAWOf78PmCBGCRmewEsgE2MjIwMzM4LmFuZHJvaWQuY29tLnZpYmVyLnZvaXAuYWRzZW5zZWZvcm1vYmlsZWFwcHMuY29tugEJZ2ZwX2ltYWdlyAEJ2gE-aHR0cDovLzIyMDMzOC5hbmRyb2lkLmNvbS52aWJlci52b2lwLmFkc2Vuc2Vmb3Jtb2JpbGVhcHBzLmNvbS-YAsgBwAIC4AIA6gIfLzY1NjU2MjYzL3Rlc3QvVGltZV9PdXRfMzAweDI1MPgC_NEekAOaCJgD0AWoAwHIAwLgBAHSBQYQvdenqhGQBgGgBjvYBgLYBwDgBx_yBwIgAdIIBwiAARABGAE","is_active_view_immediate_enabled":true,"activeview_cpm_urls":[],"active_experiment_ids":"","activeview_cid":"CAASUeRosf6NHpD3haoD6Hs7FeKRN3UOiX3uvD2Rjlflkl6up87tCfD5lMj3A7hO1JNP3b6C_3ptfeOEU44zDYfwEBdpj3HGy18gKYjKinIQLOpoVw"},"timestamp":489872398,"adFormat":"300x250_as","hashCode":"0307fc59-3858-4be2-9ad6-f286cf9ed0ae","isMraid":true,"isStopped":false,"isPaused":false,"isNative":false,"isScreenOn":true,"appMuted":false,"appVolume":1,"deviceVolume":0.800000011920929,"windowVisibility":8,"isAttachedToWindow":false,"viewBox":{"top":0,"bottom":569,"left":0,"right":320},"adBox":{"top":0,"bottom":0,"left":0,"right":0},"globalVisibleBox":{"top":0,"bottom":0,"left":0,"right":0},"globalVisibleBoxVisible":false,"localVisibleBox":{"top":0,"bottom":0,"left":0,"right":0},"localVisibleBoxVisible":false,"hitBox":{"top":0,"bottom":0,"left":0,"right":0},"screenDensity":1.5,"isVisible":false}]});
05-06 13:08:56.252 236-7099/? I/MAL-RDS:  (        ru_syssig_hndler,  493) [RDS-I][ru_syssig_hndler] Send Event: 9089 
05-06 13:08:56.272 236-578/? D/MAL-RDS:  (     ru_wsl_poll_wpainfo,  727) [RDS-D][RDS][RU][ru_wsl_poll_wpainfo]socket recv pktlen(48) 
     (rds_ru_ws_rssi_timer_exp,  841) [RDS-D][RU][rds_ru_ws_rssi_timer_expire_hdlr][RDS] get rssi = -56, snr = 9999 
05-06 13:08:56.273 236-578/? I/MAL-RDS:  (          ru_get_netstat, 6371) [RDS-I][RU][ru_get_netstat] netstat <thrghpt, pkterrt>, wifi <295, 0%>, mobile <0, 0%>
     (  rds_ru_wifi_status_ind, 1518) [RDS-I][RU][EVENT_RU_WS_WIFI_STATUS_IND] fgwifi_en:1(no use) i4wifirssi:0xffffffc8 i4wifisnr:0x270f
     (  rds_ru_ims_vops_update, 5726) [RDS-I][RU][rds_ru_ims_vops_update][RDS IMS]IMS VOPS IE is Disabled, Update to RPL<0>:(254,254), <1>:(254,254), <2>:(254,254)
05-06 13:08:56.274 236-578/? I/MAL-RDS:  (          rds_ru_rpl_gen, 5977) [RDS-I][RU][rds_ru_rpl_gen][RDS] Current policy: fgimsolte_en<0>, fgwfc_en<0>, erdspolicy<3>,||Threshold i4wifirssih<-75>, i4wifirssil<-85>, i4wifirssih_ho<-78>, i4wifirssil_ho<-88>, i4wifisnrh<10>, i4wifisnrl<6>||Threshold i4ltersrph<-106>, i4ltersrpm<-111>, i4ltersrpl<-116>, i4ltersrqh<5>, i4ltersrqm<3>, i4ltersrql<1>||Threshold i4utranrscph<-104>, i4utranrscpl<-110>, i4gsmrssih<-94>, i4gsmrssil<-102>||current rds ru status: i4wifirssi<-56>, i4wifisnr<9999>, i4ltersrp<-99>, i4ltersrq<40>, i4utranrscp<-99>, i4gsmrssi<-96>, u4active_ran<262147>||current wifi backhaul : rtp_plr<0>, rtp_jitter<0>, ping_ind<0>||pcscf acc stat : volte<1>, wfc<1> || wifi acc_ctrl:<0>, || current MD stat : MD1 roam <0>, ||Call stat : IR92<0>, IR94<0>, SMS over IP<0>
     (          rds_ru_rpl_gen, 5994) [RDS-I][RU][RDS IMS/MMS][rds_ru_rpl_gen][OP-0] Ori:(254,254)/(1,255) New:(254,254)/(1,255)||[RU][RDS IMS/MMS WIFI]Ori:(254,254)/(1,255) New:(254,254)/(1,255)||[RU][RDS IMS/MMS CELL]Ori:(254,254)/(1,255) New:(254,254)/(1,255)
05-06 13:08:56.307 24973-24973/com.example.babara.apointee D/AndroidRuntime: Shutting down VM
05-06 13:08:56.324 25166-25166/? D/dumpsys: dumpsys start
05-06 13:08:56.336 11433-11433/? D/WebView: evaluateJavascript=AFMA_updateActiveView({"units":[{"afmaVersion":"afma-sdk-a-v12529018.11020000.1","activeViewJSON":{"click_string":"BM1YBiHPsWvvZBdOmoAPAtK7IBgCd7P2n-wYAABABOAHIAQnIAwLgBAOIBc3mi4wFoAZM0ggFCIABEAE,BwsSviHPsWriuA4S9oAOvhIHQBJeF7ZxFAAAAEAEgx4v0SzgAWOf78PmCBGCRmewEsgE2MjIwMzM4LmFuZHJvaWQuY29tLnZpYmVyLnZvaXAuYWRzZW5zZWZvcm1vYmlsZWFwcHMuY29tugEJZ2ZwX2ltYWdlyAEJ2gE-aHR0cDovLzIyMDMzOC5hbmRyb2lkLmNvbS52aWJlci52b2lwLmFkc2Vuc2Vmb3Jtb2JpbGVhcHBzLmNvbS-YAsgBwAIC4AIA6gIfLzY1NjU2MjYzL3Rlc3QvVGltZV9PdXRfMzAweDI1MPgC_NEekAOaCJgD0AWoAwHIAwLgBAHSBQYQvdenqhGQBgGgBjvYBgLYBwDgBx_yBwIgAdIIBwiAARABGAE","is_active_view_immediate_enabled":true,"activeview_cpm_urls":[],"active_experiment_ids":"","activeview_cid":"CAASUeRosf6NHpD3haoD6Hs7FeKRN3UOiX3uvD2Rjlflkl6up87tCfD5lMj3A7hO1JNP3b6C_3ptfeOEU44zDYfwEBdpj3HGy18gKYjKinIQLOpoVw"},"timestamp":489872608,"adFormat":"300x250_as","hashCode":"0307fc59-3858-4be2-9ad6-f286cf9ed0ae","isMraid":true,"isStopped":false,"isPaused":false,"isNative":false,"isScreenOn":true,"appMuted":false,"appVolume":1,"deviceVolume":0.800000011920929,"windowVisibility":8,"isAttachedToWindow":false,"viewBox":{"top":0,"bottom":569,"left":0,"right":320},"adBox":{"top":0,"bottom":0,"left":0,"right":0},"globalVisibleBox":{"top":0,"bottom":0,"left":0,"right":0},"globalVisibleBoxVisible":false,"localVisibleBox":{"top":0,"bottom":0,"left":0,"right":0},"localVisibleBoxVisible":false,"hitBox":{"top":0,"bottom":0,"left":0,"right":0},"screenDensity":1.5,"isVisible":false}]});
05-06 13:08:56.337 11433-11433/? D/WebView: evaluateJavascript=AFMA_updateActiveView({"units":[{"afmaVersion":"afma-sdk-a-v12529018.11020000.1","activeViewJSON":{"click_string":"BM1YBiHPsWvvZBdOmoAPAtK7IBgCd7P2n-wYAABABOAHIAQnIAwLgBAOIBc3mi4wFoAZM0ggFCIABEAE,BwsSviHPsWriuA4S9oAOvhIHQBJeF7ZxFAAAAEAEgx4v0SzgAWOf78PmCBGCRmewEsgE2MjIwMzM4LmFuZHJvaWQuY29tLnZpYmVyLnZvaXAuYWRzZW5zZWZvcm1vYmlsZWFwcHMuY29tugEJZ2ZwX2ltYWdlyAEJ2gE-aHR0cDovLzIyMDMzOC5hbmRyb2lkLmNvbS52aWJlci52b2lwLmFkc2Vuc2Vmb3Jtb2JpbGVhcHBzLmNvbS-YAsgBwAIC4AIA6gIfLzY1NjU2MjYzL3Rlc3QvVGltZV9PdXRfMzAweDI1MPgC_NEekAOaCJgD0AWoAwHIAwLgBAHSBQYQvdenqhGQBgGgBjvYBgLYBwDgBx_yBwIgAdIIBwiAARABGAE","is_active_view_immediate_enabled":true,"activeview_cpm_urls":[],"active_experiment_ids":"","activeview_cid":"CAASUeRosf6NHpD3haoD6Hs7FeKRN3UOiX3uvD2Rjlflkl6up87tCfD5lMj3A7hO1JNP3b6C_3ptfeOEU44zDYfwEBdpj3HGy18gKYjKinIQLOpoVw"},"timestamp":489872608,"adFormat":"300x250_as","hashCode":"0307fc59-3858-4be2-9ad6-f286cf9ed0ae","isMraid":true,"isStopped":false,"isPaused":false,"isNative":false,"isScreenOn":true,"appMuted":false,"appVolume":1,"deviceVolume":0.800000011920929,"windowVisibility":8,"isAttachedToWindow":false,"viewBox":{"top":0,"bottom":569,"left":0,"right":320},"adBox":{"top":0,"bottom":0,"left":0,"right":0},"globalVisibleBox":{"top":0,"bottom":0,"left":0,"right":0},"globalVisibleBoxVisible":false,"localVisibleBox":{"top":0,"bottom":0,"left":0,"right":0},"localVisibleBoxVisible":false,"hitBox":{"top":0,"bottom":0,"left":0,"right":0},"screenDensity":1.5,"isVisible":false}]});

    --------- beginning of crash
05-06 13:08:56.350 24973-24973/com.example.babara.apointee E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.babara.apointee, PID: 24973
    android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1318)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
        at java.net.InetAddress.getAllByName(InetAddress.java:757)
        at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:187)
        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:156)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:98)
        at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:372)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:355)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:273)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:474)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)

可以通过浏览器手动访问该服务器地址。我已经获得了INTERNET和ACCESS_NETWORK_STATE的使用许可。

有人可以在这里指出我的问题。 (目前使用Device with Android Version 7.0进行测试)

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.babara.apointee"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    ...
}

dependencies {
    implementation 'com.android.support:appcompat-v7:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation files('libs/json-simple-1.1.jar')
}

2 个答案:

答案 0 :(得分:2)

您正尝试在主线程上执行网络操作。您需要在AsyncTask

中编写该代码
private class NetworkOperation extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        //Add your network code here
    }      

    @Override
    protected void onPostExecute(String result) {

    }
}

然后在onCreate()中添加:

new NetworkOperation.execute("");

答案 1 :(得分:1)

NetworkOnMainThread异常是因为您尝试在主线程中执行网络操作(无效)。

要执行网络操作,您必须使用AsyncTask

Here它可以是您正在寻找的类似主题和解决方案。