2013-07-05 60 views
-4

它只是退出。有什麼問題 ?下載不工作

我找不到任何錯誤。

如果有更好的方法來將XML下載到輸入流,請讓我知道。

還是一個很好的方式來讀取3首或更多個XML同時

package com.some.some; 


import java.io.IOException; 
import java.io.InputStream; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpStatus; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

import android.os.Bundle; 
import android.app.Activity; 
import android.util.Base64; 
import android.view.Menu; 
import android.view.View; 

public class Login extends Activity { 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
     InputStream stream1 = downloadXmlFileStreamUsingUrl("URL IS CORRECT :|"); 
     // Parse check is login or not ... 
    } 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.login, menu); 
    return true; 
} 
public InputStream downloadXmlFileStreamUsingUrl(final String url) { 



    final HttpGet getRequest = new HttpGet(url); 
    String encodedStr = Base64.encodeToString("user:pass".getBytes(), 0); 
    getRequest.setHeader("Authorization", "Basic " + encodedStr); 
    HttpClient client = null; 
    try { 
     client = new DefaultHttpClient(); 
     client.getConnectionManager(); 
     final HttpResponse getResponse = client.execute(getRequest); 
     final int statusCode = getResponse.getStatusLine().getStatusCode(); 

     if (statusCode != HttpStatus.SC_OK) { 
     return null; 
     } 

     final HttpEntity getResponseEntity = getResponse.getEntity(); 
     final InputStream content = getResponseEntity.getContent(); 
     return content; 

    } catch (final IOException e) { 
     getRequest.abort(); 
    } 
    finally { 
      client.getConnectionManager().shutdown(); 
     } 

     return null; 

     } 

} 
+1

查看日誌併發布。 – ben75

回答

2

你要了解的第一件事是,我們必須進行網絡操作。

關於谷歌開發人員文檔,他們已經解釋了一步一步的過程,這裏是the link,這裏是一個更重要的關於我們執行的網絡操作的link

因爲您發佈的代碼我認爲您的運行網絡運行在主線程

0

我假設你得到NetworkOnMainThreadException,因爲正試圖從UI訪問網絡。
從Android 3.0開始,網絡訪問應該在單獨的線程上完成。換句話說,downloadXmlFileStreamUsingUrl()應該在一個單獨的線程中運行。
您可以使用AsyncTask來達到此目的。