2017-07-27 115 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); 
     }