HttpUrlConnection详解

首先注意添加权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Android提倡使用HttpUrlConnection而不是HttpClient

HttpUrlConnection更灵活

public class MainActivity extends ActionBarActivity {

    TextView outputText;
    EditText inputText;
    Button button;
    ImageView imageView;
    String string="http://tieba.baidu.com/";
    URL url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        inputText=(EditText) findViewById(R.id.input_text);
        outputText=(TextView) findViewById(R.id.outputView);
        button=(Button) findViewById(R.id.button);
        imageView=(ImageView) findViewById(R.id.imageView);

        inputText.setText(string);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //很重要! 判断是否联网
                ConnectivityManager connMgr = (ConnectivityManager)
                        getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isConnected()) {
                    //开始异步任务,参数就是你输入的网址
                    new DownloadWebpageTask().execute(inputText.getText().toString());
                } else {
                    outputText.setText("No network connection available.");
                }
            }
        });
    }

    class  DownloadWebpageTask extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... params) {
            String result="";
            try {
                //只有一个参数,params[0]就是传入的网址
                result=downLoadUrl(params[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //这里 s 就是上面返回的result
            outputText.setText(s);
        }
    }

    //传入String,网页内容以String的形式返回
    public String  downLoadUrl(String url) throws IOException
    {
        InputStream inputStream=null;
        HttpURLConnection httpURLConnection=null;
        String result="";

        try {
            //注意,传入url是String,把url转成URL格式
            URL mUrl=new URL(url);
            //获取实例
            httpURLConnection= (HttpURLConnection) mUrl.openConnection();
            httpURLConnection.setReadTimeout(10000 /* milliseconds */);
            httpURLConnection.setConnectTimeout(15000 /* milliseconds */);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);//下载权限
            httpURLConnection.setDoOutput(true);//上传权限
            // Starts the query
            httpURLConnection.connect();
            //返回值,http状态返回代码 2xx (成功)  http状态返回代码 4xx(请求错误)比如著名的404,是(未找到) 服务器找不到请求的网页。
            int response = httpURLConnection.getResponseCode();
            Log.d("SJJ", "The response is: " + response);

            inputStream = httpURLConnection.getInputStream();

            InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            String str="";
            while ((str=bufferedReader.readLine())!=null)
            {
                result+=str;
            }
        }finally {
            //关闭inputStream
            if(inputStream!=null)
                inputStream.close();
        }
        return result;
    }


点击button,显示网页内容



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值