我正在使用HttpUrlConnection
连接到服务器。问题是我通过wifi连接到路由器。因此,我在我的设备中看到了网络。但是路由器没有连接到任何互联网输入,并且连接进入无限循环。这是代码 private String getHttpResponse(final String srcUrl) {
HttpURLConnection urlConnection = null;
FileOutputStream fos = null;
try {
URL url = new URL(srcUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(TIMEOUT);
urlConnection.setReadTimeout(TIMEOUT);
urlConnection.setRequestProperty("Content-Type", "application/json");
mETag = readETagFromPrefForCategory();
urlConnection.setRequestProperty("If-None-Match", mETag);
Log.v("abcd","####### before connection ######");
urlConnection.connect();
Log.v("abcd","####### after connection ######");
mETag = urlConnection.getHeaderField("ETag");
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
Log.v("online","not modifed");
return null;
}
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.w(TAG, "Bad response [" + urlConnection.getResponseCode() + "] from (" + srcUrl + ")");
return null;
}
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
fos = createJson();
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
if(fos != null)fos.write(line.getBytes());
}
if(fos != null)writeETagForCategory(mETag);
if (rd != null) {
Log.v("online","buffered reader closed");
rd.close();
}
return sb.toString();
} catch (UnknownHostException e) {
Log.e("Error: ", "Message - " + e.getMessage());
} catch (MalformedURLException e) {
Log.e("Error: ", "Message - " + e.getMessage());
} catch (IOException e) {
Log.e("Error: ", "Message - " + e.getMessage());
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}