Android,我无法轻松阅读任何网页

时间:2013-09-14 06:44:38

标签: java android httpconnection

我正在尝试以最简单的方式连接任何网页。我了解到我必须使用AsyncTask但我之前想要看到这份工作。

package com.example.duzbaglanti;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {



    String biyazi = "ggg";
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        tv = (TextView) findViewById(R.id.textView1);
        Button benimtus = (Button) findViewById(R.id.button1);

        benimtus.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                tv.setText(biyazi);
            }
        });



        HttpURLConnection benimconnection = null;
        try {
            URL benimurl = new URL("anypage");
            benimconnection = (HttpURLConnection) benimurl.openConnection();
            int sonuckodu = benimconnection.getResponseCode();
            if(sonuckodu == HttpURLConnection.HTTP_OK) {
                InputStream benimin = new BufferedInputStream(benimconnection.getInputStream());
                biyazi = benimin.toString();

                ///////
            }
        }
        catch (Exception e) {
            Log.d("baglantihatasi","hata oldu",e);
        }
        finally { benimconnection.disconnect(); }




    }

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

}

当我点击按钮时,我的字符串变为'Java.io.BufferedInputStream@4177b2a8'而不是我的网页输出。有什么不对?

2 个答案:

答案 0 :(得分:0)

您是否查看了BufferedInputStream#toString()的实现?

InputStream benimin = new BufferedInputStream(benimconnection.getInputStream());
biyazi = benimin.toString();

实际上并没有。因此,方法调用遵循Object#toString(),因为这是第一个可用的实现父类方法。这是实现的

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

换句话说,它与InputStream的内容无关。您需要实际将流读入可能的字节数组,然后将其转换为StringHere's one way.

答案 1 :(得分:0)

检查清单文件,是否已为清单文件添加了Internet权限,如果没有,请添加它。那就行了!