Volley框架进行网络请求,简单的请求方法,还望各位大神多多指教】
实现方法:需要一个第三方jar包
package com.example.volleyhttp;
import java.util.HashMap;
import java.util.Map;
import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
/**
*
* 使用volley实现网络请求
* @author 浅议爱
*
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//定义网络请求方法
gethttp();//请求方式get
}
private void gethttp() {
// TODO Auto-generated method stub
//定义接口
RequestQueue queue = Volley.newRequestQueue(this);
String url="http://www.2cto.com/kf/201508/437176.html";
StringRequest request=new StringRequest(Method.GET, url, new Listener<String>() {
//请求成功
@Override
public void onResponse(String response) {
// TODO Auto-generated method stub
String str = response.toString();//请求成功后,接口里面的数据
// Log.i("TAG", str.toString());
Log.i("TAG", response+"=======response=======");
}
//请求失败
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"请求失败", 0);
}
})
//添加请求参数,使用map集合添加,直接写在该方法体里面
{
@Override
protected Map<String, String> getPostParams()
throws AuthFailureError {
// TODO Auto-generated method stub
Map<String, String> map=new HashMap<String, String>();
map.put("name", "武小鹏");
return map;
}
};
queue.add(request);
}
}