Volley 网络请求 (常用)

 package com.example.administrator.myapplication.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.administrator.myapplication.R;

public class VolleyActivity extends AppCompatActivity {
    WebView webView;
    Button volleyBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_volley);
        webView = (WebView) findViewById(R.id.volleyWebView);
        volleyBtn = (Button) findViewById(R.id.pressVolley);
        volleyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doStringVolley();
            }
        });
    }

    private void doStringVolley() {
        //1.创建请求队列
        RequestQueue queue = Volley.newRequestQueue(this);
        //2.创建请求对象
        StringRequest request = new StringRequest(
                "http://www.baidu.com",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String s = response;
                        webView.getSettings().setDefaultTextEncodingName("utf-8");
                        webView.getSettings().setJavaScriptEnabled(true);
                        webView.loadDataWithBaseURL(null,s,"text/html","utf-8",null);
                    }
                }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            webView.loadDataWithBaseURL(null,"网络连接失败","text/html","utf-8",null);
                        }
                }
        );
        //3.把请求对象放入队列
        queue.add(request);
    }
}

 

posted @ 2016-09-21 17:18  me丶不是好人  阅读(179)  评论(0编辑  收藏  举报