java - android - 如何获取网络源代码? (空异常)

标签 java android httpwebrequest httpwebresponse

我想获取网页源代码(这是我用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>

问候。

最佳答案

您有一个 NetworkOnMainThreadExceptionLogCat 中查看它。您必须将代码放入 AsyncTaskthread 中。

关于java - android - 如何获取网络源代码? (空异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25209882/

相关文章:

c# - 如何使用 httpWebRequest 设置请求体

java 7 uuid 错误?

java - 如何同时并行调用多个REST服务?

java - 索引越界异常java

android - 如何将 react native android 应用程序提交到 playstore?

android - 应用程序启动器在 Android 中从头重新加载

c# - 发送多个帖子请求

java - com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : Communications link failure

java - android 字符串数字格式异常

http - 为 GET 请求设置的正确 Content-Length 是多少?