我正在与美国地质勘探局API一个HttpURLConnection类。这是我的网址:
“Qazxswpoi”
彻底调试后,看来以后connection.connect连接失败和jsonResponse是空的。
https://earthquake.usgs.gov/fdsnws/event/1/queryformat=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10
public static String makeHttprequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection connection = null;
InputStream stream = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(1000000);
connection.setConnectTimeout(1500000);
connection.connect();
stream = connection.getInputStream();
jsonResponse = readfromstream(stream);
} catch (IOException e) {
Log.e("IOException", "Error while making request");
}
return jsonResponse;
}
一切看起来都不错。在我看来,你在你正在运行的设备没有互联网连接。也许你正在使用您的计算机没有连接到网络仿真器。
请尽量在实际运行设备。它的工作非常适合我。
一些建议,请尽量使用库,如改造或OkHttp。它们比这些旧的方式非常容易得多,更加便利。
如果你坚持使用HttpURLConnection类,请尝试以下
This is Log
或者更正式使用HttpURLConnection类的,访问这里。它显示了几个正确使用HttpURLConnection类的API。
URL url = new URL(yourUrlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
只是想尽自己的真实设备的一切应用程序正在按预期可能有问题模拟器。