Android网络开发之Volley--Volley基本用法StringRequest(一)

时间:2022-03-15 08:54:03

1、StringRequest用法

主要分为3步:

(1)、实例化一个RequestQueue对象

(2)、设置StringRequest对象参数,并将StringRequest对象加入RequestQueue队列

(3)、执行start()方法

public class StringActivity extends Activity {
private TextView mTvShow; private RequestQueue requestQueue; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_string); initView();
} public void initView(){
mTvShow = (TextView) findViewById(R.id.tv_string); requestQueue = Volley.newRequestQueue(getBaseContext());
requestQueue.add(stringRequest);
requestQueue.start();
} /** StringRequest请求,默认为GET*/
public StringRequest stringRequest = new StringRequest("http://www.baidu.com", new Listener<String>() { @Override
public void onResponse(String response) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), response, Toast.LENGTH_SHORT).show();
} }, new ErrorListener(){ @Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.e("StringRequest", error.toString());
} }); /** StringRequest的Post请求,但是需要重写匿名类getParams()*/
StringRequest stringRequest1 = new StringRequest(Method.POST, "http://www.baidu.com", new Listener<String>() { @Override
public void onResponse(String response) {
// TODO Auto-generated method stub
mTvShow.setText(response);
}
}, new ErrorListener(){ @Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.e("StringRequest", error.toString());
} }){
// 需要重写获取参数的函数,可以向服务器提交参数
protected Map<String,String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("wd", "开始吗");
map.put("rsv_spt", "不开始啦");
return map;
};
};
}

2、不要忘记加入网络访问权限

<uses-permission android:name="android.permission.INTERNET"/>

3、参考博文:

http://blog.csdn.net/guolin_blog/article/details/17482095/