我試圖通過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 "";
}
}
我曾嘗試使用HttpURLConnection
和URLConnection
,他們既不是可行的。我使用調試來檢查代碼。該方案未能在
private String getWebResponse(String urlStr) {
...
InputStream is = httpConn.getInputStream();
....
}
httpConn.getInputStream()
不斷返回null
。
請幫我脫身!
'該文件的URL是:「192.168.43.157:8080/apk/list.txt」'。不,那是nu網址。該網址是「http://192.168.43.157:8080/apk/list.txt」。 – greenapps
謝謝。但是,如果我擺脫「http:」。該程序在「URL url = new URL(urlStr);」引發異常。 「InputStream is = httpConn.getInputStream();」的原始異常提示 –
誰讓你擺脫http://? – greenapps