2017-07-27 185 views
0

我寫了一個android應用程序,它運行良好,然而,最近,我發現它不工作。從下面的鏈接我的應用程序解析JSON代碼: http://opendata.epa.gov.tw/ws/Data/RainTenMin/?%24format=jsonandroid HttpURLConnection不斷得到302

我發現,爲什麼我的應用程序不能正常工作的原因是,響應代碼是302,所以我谷歌在互聯網上,並使用的getHeaderField(「位置」)在我的代碼 我發現重定向的URL是 https://opendata.epa.gov.tw/ws/Data/RainTenMin/?%24format=json

所以我改變了我的解析鏈接直接鏈接以https,然而,這一次, HttpURLConnection的拋出IOEexception,我怎麼能解決這個問題,感謝您的幫幫我。

下面是我的代碼拋出異常:下面

private static String httpRequest(URL rurl) throws IOException{ 
     String response = ""; 

     if (rurl == null) { 
      return response; 
     } 
     HttpURLConnection connection = null; 
     InputStream inputStream = null; 
     try { 
      connection = (HttpURLConnection) rurl.openConnection(); 
      connection.setConnectTimeout(20000); 
      connection.setRequestMethod("GET"); 
      connection.setReadTimeout(25000); 
      connection.connect(); 

      //200 means correctly connected 
      int responseCode = connection.getResponseCode(); 

      if (responseCode ==200) { 
       inputStream = connection.getInputStream(); 
       response = readStream(inputStream); 
      } 
      else { 

       MainActivity.connect=false; 
       Log.i(logtag, "Error!! Response code is " + responseCode); 
      } 
     } 
     catch (IOException e) { 
      MainActivity.connect=false; 
      Log.e(logtag, "bad internet!!");} 
     finally { 
      if (inputStream != null) { 
       inputStream.close(); 
      } 
      if (connection != null) { 
       connection.disconnect(); 
      } 
     } 
     return response; 
    } 

是錯誤的logcat的:

E/query: bad internet!! 
+0

如果你是https,然後用httpsconnection改變它(https://developer.android如果你不想嘗試[改造](()/(/)/參考/ javax /網絡/ ssl/HttpsURLConnection.html) – Ozan

+0

請添加錯誤的logcat – aliaksei

+0

不想離題,但是,爲什麼你不嘗試[改造] http://square.github.io/retrofit/)? – crgarridos

回答

0

什麼你得到一個javax.net.ssl.SSLHandshakeException。

你可以找到關於如何解決這個問題,在這裏一些有用的信息: How to solve javax.net.ssl.SSLHandshakeException Error?

摘錄:

TrustManager[] trustAllCerts = new TrustManager[]{ 
       new X509TrustManager() { 

        public java.security.cert.X509Certificate[] getAcceptedIssuers() 
        { 
         return null; 
        } 
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) 
        { 
         //No need to implement. 
        } 
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) 
        { 
         //No need to implement. 
        } 
       } 
     }; 

     // Install the all-trusting trust manager 
     try 
     { 
      SSLContext sc = SSLContext.getInstance("SSL"); 
      sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 
     } 
     catch (Exception e) 
     { 
      System.out.println(e); 
     } 
相關問題