2012-09-10 85 views
0

我正在使用HttpUrlConnection的应用程序,与服务器连接的漂亮,但从其中获取数据时说连接超时IOException。Android httpUrlConnection连接到服务器,但不是互联网

互联网,&网络权限已在android.manifest中设置;有没有酒吧出现在Android模拟器(这是否说什么)。

阅读在developer.android.com: 模拟器的功能限制包括: - 用于确定网络连接状态 不支持 - 和其他几个....

任何帮助将得到高度赞赏。而且我没有真正的设备来测试它。

接收到的服务器信息确实打印在logcat中。

谢谢...

下面是代码:

URL url = new URL(urlString); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
try { 
    Log.i(INFO_TAG, "Received server:" + conn.toString()); 
    conn.setInstanceFollowRedirects(true); 
    conn.setRequestMethod("GET"); 
    conn.setRequestProperty("Content-length", "0"); 
    conn.setUseCaches(false); 
    conn.setAllowUserInteraction(false); 
    conn.setConnectTimeout(25000 /* milliseconds */); 
    conn.setReadTimeout(15000/* 10000 *//* milliseconds */); 
    // conn.setDoInput(true); 
    // Starts the query 
    conn.connect(); 
    status = conn.getResponseCode(); 
    Log.d(DEBUG_TAG, "Status recevied is: " + conn.getResponseCode()); 
    responseCode = status; 
    if (responseCode == 200) { 
     Log.i(INFO_TAG, "URL Connection OK"); 
     contentIs = conn.getInputStream(); 
     BufferedReader reader = new BufferedReader(
       new InputStreamReader(contentIs)); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      builder.append(line); 
      Log.i(INFO_TAG, "Data Read is: " + line); 
     } 
    } else { 
     Log.d(DEBUG_TAG, "Could not read data from web server"); 
     Log.e(ConnectAndGetData.class.toString(), 
      "Failed to download content"); 
    } 
}// end of try 
catch (Exception ex) { 
    // This is currently being printout 
    Log.d(DEBUG_TAG, "Received an exception" + ex.toString(), ex); 
    ex.printStackTrace(); 
    throw new IOException("Error Connecting" + ex.toString());// "Error connecting"); 
} finally { 
    if (contentIs != null) { 
     contentIs.close(); 
     conn.disconnect(); 
    } 
} 

一两件事,因为,它抛出一个连接超时异常不会在调试该行信息被打印: Log.d (DEBUG_TAG,“收到的状态是:”+ conn.getResponseCode());

+0

上传带问题的代码。 – Lucifer

+0

嗨路西法,已经上传代码的问题:)我希望有人可以暗示的东西在这里... – AliR

+0

我想我得到了答案,尝试'conn.close();'而不是'如果'conn.disconnect(); “这两种方法都有不同的含义。 – Lucifer

回答

1

问题不在于上面的代码,它是服务器代码(主要罪魁祸首)。现在实现了一个Web服务,上面的代码工作正常。

感谢所有评论...

0

您需要这条线

conn.setConnectTimeout(25000 /* milliseconds */); 
conn.setReadTimeout(15000/*10000*/ /* milliseconds */); 

其设置指示此URLConnection是否允许输入后旗写

conn.setDoInput(true);

+0

对不起,要更清楚;我已经试过,但没有变化 – AliR

+0

嗨,所以我有点针对性的问题;上面的代码无法连接到服务器。任何方向?在服务器端,它确实发现android已经连接,然后发送数据。 – AliR

0

模拟器无法从服务器接收任何响应。我认为你的网络连接存在问题。检查您的代理设置。

+0

代理设置,在哪里? – AliR

+0

你在公司网络内吗? – ponraj

+0

是什么?我想你应该问这个问题:是的,我使用的服务器与模拟器在同一台机器上。 – AliR

相关问题