2013-02-22 44 views
1

我試圖構建一個使用REST Api上載文件的IntentService。從IntentService調用時,HttpURLConnection返回404

我可以從我的主Activity啓動IntentService,IntentService可以將消息傳回Activity,所以我知道IntentService正在工作。

我的問題是,當我運行這段代碼:

@Override 
protected void onHandleIntent(Intent intent) {  
    // do the uploading stuff  
    try {   
     URL url = new URL(this.url + fileName); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("PUT"); 
     conn.setDoOutput(true); 

     BufferedInputStream buffInputStream = new BufferedInputStream(new FileInputStream(filePath)); 
     BufferedOutputStream buffOutputStream = new BufferedOutputStream(conn.getOutputStream()); 
     HttpUtils.copyBufferStream(buffInputStream, buffOutputStream); 

     if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){ 
      BufferedInputStream responseBufferedInput = new BufferedInputStream(conn.getInputStream()); 
      byte[] body = HttpUtils.readStream(responseBufferedInput);       
      result = HttpUtils.convertBytesToString(body);    
      Log.e("Result:", result); 
     }else{ 
      Log.e("conn.getResponseCode()", Integer.toString(conn.getResponseCode())); 
     }  
    } catch (IOException e) { 
     e.printStackTrace(); 
    }          
} 
在IntentService onHandleIntent方法

,我總是得到一個404(或FileNotFoundException異常時不檢查conn.getResponseCode())。

在我的主Activity中調用完全相同的代碼,上傳文件併成功完成。

我不知道爲什麼會發生這種情況?有任何想法嗎?

回答

5

嘗試打印你試圖打開URL,你可能會發現,有一些毛病......也許這只是一個缺少斜槓;-)

404是HTTP錯誤未找到意味着該URL在該服務器上無效。

+0

好點。如果URL格式不正確或編碼不正確,這肯定會返回404。在這種情況下,url完全是它應該的。我在主Activity中的相同HttpURLConnection代碼中測試了相同的url,並且在瀏覽器中的REST Api控制檯中測試了相同的url,並且它工作正常。 – speedynomads 2013-02-22 11:25:37

+0

相關提示!祝你好運! – 2013-02-22 12:17:22

+2

Doh!事實證明,這個網址實際上是錯誤的,實際上有一個缺失的斜線;謝謝! – speedynomads 2013-02-22 12:25:19