【发布时间】:2017-07-27 21:56:57
【问题描述】:
我写了一个安卓应用程序,之前它运行良好,但是,最近,我发现它不能运行。我的应用程序从以下链接解析 json 代码: http://opendata.epa.gov.tw/ws/Data/RainTenMin/?%24format=json
我发现我的应用程序不工作的原因是响应码是302,所以我在互联网上google,并在我的代码中使用getHeaderField(“Location”) 我发现重定向的网址是 https://opendata.epa.gov.tw/ws/Data/RainTenMin/?%24format=json
所以我将解析 url 更改为带有 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!!
【问题讨论】:
-
如果你用https改了,那就用httpsconnection (developer.android.com/reference/javax/net/ssl/…)
-
请添加错误的logcat
-
不想跑题,但是,你为什么不试试retrofit?
-
@Ozn 不工作,仍然得到 IOE 异常
-
用 POST 改变 GET 方法