2010-07-23 25 views

回答

1
 String url = "http://google.com"; 
    HttpConnection _conn = (HttpConnection) Connector.open(url); 
    int rc = _conn.getResponseCode(); 
    System.out.println("RC : " + rc); 
    if(rc != 200) 
     return; 


    InputStream is = null; 
    byte[] result = null; 
    is = _conn.openInputStream(); 
    // Get the ContentType 
    String type = _conn.getType(); 


    // Get the length and process the data 
    int len = (int)_conn.getLength(); 
    if (len > 0) { // If data lenght is defined 
     int actual = 0; 
     int bytesread = 0; 
     result = new byte[len]; 
     while ((bytesread != len) && (actual != -1)) { 
      actual = is.read(result, bytesread, len - bytesread); 
      bytesread += actual; 
     } 
    }else { // If no data lenght is not defined in HTTP response 
     // Data accumulation buffer (for whole data) 
     NoCopyByteArrayOutputStream outputStream = new NoCopyByteArrayOutputStream(1024); 
     // Receive buffer (for each portion of data) 
     byte[] buff = new byte[1024]; 
     while ((len = is.read(buff)) > 0) { 
      // Write received portion of data into accumulation stream 
      outputStream.write(buff, 0, len); 
     } 
     result = outputStream.toByteArray(); 
     System.out.println(new String(result)); 
    }