关闭

volley网络请求,get/post

33人阅读 评论(0) 收藏 举报
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
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;



public class TwoActivity extends Activity {
private String path = "http://m.yunifang.com/yunifang/mobile/goods/getall?random=9949&encode=6c2154232994e7d36ad461e3caa68ca7";
private String path1 = "http://japi.juhe.cn/health_knowledge/categoryList";
private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_two);
    tv = (TextView) findViewById(R.id.tv);

    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    /*
     * get请求方法
     */
    StringRequest request = new StringRequest(path,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    System.out.println("请求成功get" + response);
                    tv.setText(response);//更新到UI线程控件中
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    System.out.println("请求失败get");
                }
            });
queue.add(request);

/*
* post请求方法
*/

    StringRequest stringRequest = new StringRequest(Method.POST, path1,  new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            System.out.println("请求成功post : "+response);

        }
    },  new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO Auto-generated method stub
            System.out.println("请求失败post");
        }
    } ) {  
        @Override  
        protected Map<String, String> getParams() throws AuthFailureError {  
            Map<String, String> map = new HashMap<String, String>();  
            map.put("key", "77a23e1413b84844bca44a20d0d8be3a");  

            return map;  
        }  
    };  
    queue.add(stringRequest);

}

}

//由于Volley是要访问网络的,因此不要忘记在你的AndroidManifest.xml中添加如下权限:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1988次
    • 积分:326
    • 等级:
    • 排名:千里之外
    • 原创:32篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类