您现在的位置是:首页 > 文章详情

volley框架使用小Demo

日期:2018-05-26点击:545

MainActivity

public class MainActivity extends AppCompatActivity  {

private static final String URL = "https://www.baidu.com/";
private RequestQueue mQueue; // volley的请求队列
@BindView(R.id.volley_get)
Button btn;
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mQueue = Volley.newRequestQueue(getApplicationContext());
    ButterKnife.bind(this);
}

@OnClick({R.id.volley_get})
public void onClick(View v) {
    get();
}

/**
 * 创建一个请求,这里我们做一个最简单的通过GET方式请求网页源码的操作。请求成功后打印结果。
 */
private void get() {
    StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {

        @Override
        public void onResponse(String arg0) {
            //Toast.makeText(getApplicationContext(), arg0, Toast.LENGTH_LONG).show();
            textView = (TextView) findViewById(R.id.text);
            textView.setText(arg0.toString());
            //Log.d("onResponse", arg0);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError arg0) {
            //Toast.makeText(getApplicationContext(), arg0.toString(), Toast.LENGTH_LONG).show();
            textView = (TextView) findViewById(R.id.text);
            textView.setText(arg0.toString());
        }
    });
    mQueue.add(request);
}

}

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.an.volleytest.MainActivity">

<Button
    android:id="@+id/volley_get"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="get请求"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:id="@+id/text"
    android:layout_marginTop="25dp"
    android:layout_below="@+id/volley_get"
    android:layout_centerHorizontal="true" />
</RelativeLayout>
img_050b292ca8d354474894c208fda79789.png
捕获.PNG

点击按钮 hello world 替换为请求网址的html文件

原文链接:https://yq.aliyun.com/articles/681060
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章