2017-08-31 107 views
0

我試圖通過Android手機讀取遠程服務器上的文本文件中的內容。該文件的網址爲192.168.43.157:8080/apk/list.txt,我通過在PC上使用我的瀏覽器並在地址欄中粘貼了URL,測試了該服務器運行良好。Android從網絡獲取數據

我添加使用的權限:

<uses-sdk 
    android:minSdkVersion="14" 
    android:targetSdkVersion="18" /> 
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<application 
    ... 

而且這是在活動代碼

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_test); 

    String listUrl = "http://192.168.43.157:8080/apk/list.txt"; 

    String response = getWebResponse(listUrl); 
    TextView textView = (TextView) findViewById(R.id.web_response); 
    textView.setText(response); 

} 

private String getWebResponse(String urlStr) { 
    try { 
     URL url = new URL(urlStr); 
     HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 
     httpConn.setRequestMethod("GET"); 
     httpConn.setDoInput(true); 
     InputStream is = httpConn.getInputStream(); 
     InputStreamReader isr = new InputStreamReader(is, "UTF-8"); 
     BufferedReader br = new BufferedReader(isr); 
     StringBuilder response = new StringBuilder(); 
     String line = null; 
     while((line = br.readLine()) != null) { 
      response.append(line); 
     } 
     return response.toString(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return ""; 
    } 

} 

我曾嘗試使用HttpURLConnectionURLConnection,他們既不是可行的。我使用調試來檢查代碼。該方案未能在

private String getWebResponse(String urlStr) { 
    ... 
    InputStream is = httpConn.getInputStream(); 
    .... 
} 

httpConn.getInputStream()不斷返回null

請幫我脫身!

+0

'該文件的URL是:「192.168.43.157:8080/apk/list.txt」'。不,那是nu網址。該網址是「http://192.168.43.157:8080/apk/list.txt」。 – greenapps

+0

謝謝。但是,如果我擺脫「http:」。該程序在「URL url = new URL(urlStr);」​​引發異常。 「InputStream is = httpConn.getInputStream();」的原始異常提示 –

+0

誰讓你擺脫http://? – greenapps

回答

0

我建議你使用一些庫,這使得它容易 例如使用volley庫(由谷歌)

的例子:

// Instantiate the RequestQueue. 
RequestQueue queue = Volley.newRequestQueue(this); 
String url ="http://www.google.com"; 

// Request a string response from the provided URL. 
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
      new Response.Listener<String>() { 
    @Override 
    public void onResponse(String response) { 
     // get the response 
    } 
}, new Response.ErrorListener() { 
    @Override 
    public void onErrorResponse(VolleyError error) { 
     // error msg 
    } 
}); 
// Add the request to the RequestQueue. 
queue.add(stringRequest); 

,並順便說一下,如果你是使用模擬器,你應該把這個IP地址10.0.2.2

+0

事實是,我在一個阻止谷歌的大國。我沒有安裝包裝齊射。 –

0

這段代碼適合我。

 URL url; 
     HttpURLConnection urlConnection = null; 
     StringBuilder result = new StringBuilder(); 
     BufferedReader reader = null; 

     urlConnection = (HttpURLConnection) url 
         .openConnection(); 
       urlConnection.connect(); 

       InputStream in = urlConnection.getInputStream(); 
       reader = new BufferedReader(new InputStreamReader(in)); 
       //InputStreamReader isw = new InputStreamReader(in); 
       StringBuffer buffer = new StringBuffer(); 
       String line =""; 
       while ((line = reader.readLine()) != null){ 
        buffer.append(line); 
       } 

       String finalJson = buffer.toString(); 
+0

看來我們的代碼之間的區別在於你調用了方法:「urlConnection.connect()」。我已經嘗試過了,程序仍然在「InputStream in = urlConnection.getInputStream();」中引發異常 –

+0

是的,你有沒有嘗試connect()?它不起作用? – Orvenito

+0

list.txt的內容是什麼? – Orvenito

0

事實是,你就不能使用主線程以從網絡內容,我必須這樣做用「的AsyncTask」。雖然我不明白爲什麼它應該是這樣,但是在將這個過程包裝在一個AsyncTask類中之後,該程序就可以工作。當我嘗試將文件上傳到服務器時遇到了同樣的問題。但是,當我嘗試使用主線程上傳或下載時,程序會引發不同的錯誤。

沒有澱粉,我會粘貼我所做的。

public class TestActivity extends Activity { 

private TextView remoteContent; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_test); 

    String listUrl = "http://192.168.43.157:8080/apk/list.txt"; 
    remoteContent = (TextView) findViewById(R.id.web_response); 
    //String response = getWebResponse(listUrl); 
    //TextView textView = (TextView) findViewById(R.id.web_response); 
    //textView.setText(response); 

    GetApksListTask task = new GetApksListTask(); 
    task.execute(new String[]{listUrl}); 
} 


private class GetApksListTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... urls) { 
     try { 
      URL url = new URL(urls[0]); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setDoInput(true); 
      conn.setRequestMethod("GET"); 
      InputStream is = conn.getInputStream(); 
      InputStreamReader isr = new InputStreamReader(is, "UTF-8"); 
      BufferedReader br = new BufferedReader(isr); 
      StringBuilder response = new StringBuilder(); 
      String line = null; 
      while((line = br.readLine()) != null) { 
       response.append(line); 
      } 
      return response.toString(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      return ""; 
     } 
    } 

    @Override 
    protected void onPostExecute(String response) { 
     remoteContent.setText(response); 

     } 
    } 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.test, menu); 
     return true; 
    } 
}