2011-03-11 29 views
0

我是新來的黑莓berry.i我做一項任務,我有一個webservice來顯示一些url.i需要回顧它並連接到該url.i嘗試與兩個線程之一是檢索網址,另一個是連接到web服務中的url,但它顯示空指針異常。請幫助我。從webservice回收url以及如何連接到該網址

謝謝。

+4

沒有看到代碼就無法診斷這類問題。 – 2011-03-11 21:40:58

回答

0

由於您尚未發佈任何代碼,因此診斷問題非常困難。但看看下面的代碼,它試圖打開一個絕對的網址。這可能會有所幫助。

對於您的兩個連接(從Web Service返回的Web Service和URL)都使用此方法。請務必在單獨的線程中調用此方法,否則會凍結UI。

public static ResponseBean sendRequestAndReceiveResponse(
String method, String absoluteURL, String bodyData, boolean readResponseBody) 
    throws IOException 
{ 
     ResponseBean responseBean = new ResponseBean(); 
     HttpConnection httpConnection = null; 
try 
{ 
    String formattedURL = absoluteURL + "deviceside=true;interface=wifi"; // If you are using WiFi 
    //String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES 
    //String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP 

    if(DeviceInfo.isSimulator()) // if simulator is running 
     formattedURL = absoluteURL; 

    httpConnection = (HttpConnection) Connector.open(formattedURL); 

    httpConnection.setRequestMethod(method); 

    if (bodyData != null && bodyData.length() > 0) 
    {        
     OutputStream os = httpConnection.openOutputStream(); 
     os.write(bodyData.getBytes("UTF-8")); 
    }   

    int responseCode = httpConnection.getResponseCode(); 
    responseBean.setResponseCode(responseCode); 

    if (readResponseBody) 
    { 
     responseBean.setBodyData(readBodyData(httpConnection)); 
    } 
} 
catch (IOException ex) 
{      
    System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex); 
    throw ex; 
} 
catch(Exception ex) 
{      
    System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex); 
    throw new IOException(ex.toString()); 
} 
finally 
{ 
    if (httpConnection != null) 
     httpConnection.close(); 
} 

return responseBean; 
} 

public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException 
{ 
    if(httpConnection == null) 
     return null; 
StringBuffer bodyData = new StringBuffer(256);       
InputStream inputStream = httpConnection.openDataInputStream(); 

byte[] data = new byte[256]; 
int len = 0; 
int size = 0; 

while (-1 != (len = inputStream.read(data))) 
{ 
    bodyData.append(new String(data, 0, len,"UTF-8")); 
    size += len; 
} 

if (inputStream != null) 
{ 
    inputStream.close();    
} 

return bodyData; 
} 
+0

感謝您的回覆 – Kotibab 2011-03-14 16:27:55

相關問題