我正在尝试从我的Android应用程序连接到服务器并获得一些JSON响应。我正在使用HttpUrlConnection
来ping服务器。服务器运行正常,因为我在浏览器上收到响应。在下面的代码中,inputStream.available()
总是返回0,因此我无法解析我的数据。有没有办法让我得到答复?
注意:以下方法在单独的线程(AsyncTask<Void, Void, Void>
)
private void pingServer(final String serverUrl) throws IOException {
InputStream inputStream = null;
try {
final URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);// milliseconds
conn.setConnectTimeout(15000);// milliseconds
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
inputStream = conn.getInputStream();
String resp = readIt(inputStream, inputStream.available());//resp is empty :(
} catch (IOException e) {
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
private String readIt(final InputStream stream,final int len) throws IOException {
final Reader reader = new InputStreamReader(stream, "UTF-8");
final char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}