我写了一个Android应用程序,它之前运行良好,但是,最近,我发现它不起作用。我的应用程序从以下链接解析json代码: http://opendata.epa.gov.tw/ws/Data/RainTenMin/?%24format=json
我发现我的应用无法正常工作的原因是响应代码是302,所以我在互联网上谷歌,并在我的代码中使用getHeaderField(“Location”) 我发现重定向的网址是 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 :(得分: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);
}