2011-10-21 33 views
0

我想從遠程服務器下載鏡像。但每次我得到一個空指針異常。Android遠程鏡像ERROR

方法Conencting到服務器

private InputStream OpenHttpConnection(String urlString) 
    throws IOException 
    { 
    InputStream in = null; 
    int response = -1; 

    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection(); 

    if (!(conn instanceof HttpURLConnection))      
     throw new IOException("Not an HTTP connection"); 

    try{ 
     HttpURLConnection httpConn = (HttpURLConnection) conn; 
     httpConn.setAllowUserInteraction(false); 
     httpConn.setInstanceFollowRedirects(true); 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 

     response = httpConn.getResponseCode();     
     if (response == HttpURLConnection.HTTP_OK) { 
      in = httpConn.getInputStream();  
      Log.i("Download ", "Response: OK"); 
      }  
     else 
      Log.i("Download ", "Response: NOK"); 
    } 
    catch (Exception ex) 
    { 
     throw new IOException("Error connecting");    
    } 
    return in;  
} 

方法創建位圖

private Bitmap DownloadImage(String URL) 
    {   
     Bitmap bitmap = null; 
     InputStream in = null;   
    try { 
     in = OpenHttpConnection(URL); 
     Log.i("Download ", "InputStream Available: " +in.available()); 
     bitmap = BitmapFactory.decodeStream(in); 
     Log.i("Download ", "Bitmap: " +bitmap.describeContents()); 
     in.close(); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    return bitmap;     
} 

當我decodeStream空pointerException被拋出,但是當我使用不同的URL它的工作原理。

我在端口90上運行Apache。如果有的話,這也可以有效果。

回答

1

試試這個我希望工作。

用FTP將連接該代碼

public FTPClient mFTPClient = null; 

public boolean ftpConnect(String host, String username, 
           String password, int port) 
    { 
     try { 
      mFTPClient = new FTPClient(); 
      // connecting to the host 
      mFTPClient.connect(host, port); 

      // now check the reply code, if positive mean connection success 
      if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { 
       // login using username & password 
       boolean status = mFTPClient.login(username, password); 
       return status; 
      } 
     } catch(Exception e) { 
      Log.d(TAG, "Error: could not connect to host " + host); 
     } 

     return false; 
    } 

下載文件使用此代碼

public boolean ftpDownload(String srcFilePath, String desFilePath) 
{ 
    boolean status = false; 
    try { 
     FileOutputStream desFileStream = new FileOutputStream(desFilePath);; 
     status = mFTPClient.retrieveFile(srcFilePath, desFileStream); 
     desFileStream.close(); 

     return status; 
    } catch (Exception e) { 
     Log.d(TAG, "download failed"); 
    } 

    return status; 
} 
+0

@Sims是工作的罰款與您的代碼或不? – Nik88

+0

對不起,我花了很長時間回覆但是,我發現了這個問題。它在我上傳PNG圖像而不是JPEG圖像時起作用。但是我使用了和你的代碼,它確實上傳了。 – Sims

+0

@Sims如果答案對你有幫助你可以檢查答案左側的右箭頭。 – Nik88