从URL接收的问题

时间:2011-03-11 12:48:10

标签: android inputstream

您好我正在从Android设备的网址接收JSON文件。我不知道为什么我只得到JSON的第一个字符,这是一个“{”而不是 {"status":"OK","num_results":5,"results":[{"id":1,"title":"Apartamentos Campus", 然后is.available()一直返回1。 有趣的是,如果我在另一台设备上使用,它会收到所有内容。

我正在使用wifi连接。

我得到的输出是:

03-11 13:12:17.377:VERBOSE / Mixare(15816):尝试:1

03-11 13:12:17.382:VERBOSE / Mixare(15816):is.available():1

03-11 13:12:17.462:VERBOSE / Mixare(15816):尝试:1

03-11 13:12:17.482:VERBOSE / Mixare(15816):is.available():1

03-11 13:12:19.417:VERBOSE / Mixare(15816):尝试:2

03-11 13:12:19.417:VERBOSE / Mixare(15816):is.available():1 ...

这是代码:

    public InputStream getHttpGETInputStream(String urlStr, int attemps) throws Exception {     
    URL u = new URL(urlStr);
    InputStream is = null;
    try{            
        URLConnection uc = u.openConnection();          
        is =  uc.getInputStream();          
    }
    catch(Exception e){
        Log.v(MixView.TAG, "Excepcion leyendo inputStream: "+e.getMessage());           
    }
    Log.v(MixView.TAG, "attemps: "+attemps);
    Log.v(MixView.TAG, "is.available(): "+is.available());
    if(is.available() < 50 && attemps < 6){
        try {               
            Thread.sleep(2000);//para y lo vuelve a intentar descargar              
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        attemps++;      
        is.close();
        return getHttpGETInputStream(urlStr,attemps);
    }       
    return is;
}

1 个答案:

答案 0 :(得分:0)

我猜,你正在以错误的方式阅读内容。请使用以下代码:

public static final byte[] getBytes(URLConnection conn ) throws IOException {
                final InputStream inputStream = conn.getInputStream();      
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();         
                final byte[] b = new byte[256];
                int rv = 0;
                while ( ( rv = inputStream.read(b) ) != -1 ) baos.write(b, 0, rv);
                try  { inputStream.close(); } catch ( Exception e ) {};
            try  {
                final HttpURLConnection httpConn = (HttpURLConnection)conn;                     
                        httpConn.disconnect();
            }
            catch ( Exception e ) {};       
            final byte[] bytes =  baos.toByteArray();
            baos.close();
            return bytes;
        }

        public static final String getResponse(URLConnection conn) throws IOException {
                final byte[] bytes = getBytes(conn);
            final String response = new String(bytes,"UTF-8");
            return response;
        }      

...
final JSONObject responseObj = new JSONObject(getResponse(your_url_connection));
...