我想获取网页源代码(这是我用php编写的),然后它显示在textview中。但是,它始终返回 null。
我使用permisson(INTERNET),但它不起作用。
当我运行此应用程序时,TextView 显示:“Kaynak Kod: null”
这是我的 Activity 代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
try {
String source = getData("http://www.oeaslan.com/excel/index_.php?gun=1");
tv.setText("Kaynak Kod: "+source);
} catch (Exception e) {
tv.setText("Hata: "+e.getMessage());
}
}
});
}
private String getData(String url){
try{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
return html;
}catch(Exception e){
return e.getMessage();
}
}
list :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.omer.text"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
问候。
最佳答案
您有一个 NetworkOnMainThreadException
在 LogCat
中查看它。您必须将代码放入 AsyncTask
或 thread
中。
关于java - android - 如何获取网络源代码? (空异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25209882/