Volley框架模式

Volley-GETandroid

import com.android.volley.toolbox.Volley;


public class JDKActivity extends AppCompatActivity {

    EditText et1;
    RequestQueue requestQueue;
    //請求隊列
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jdk);
        et1=(EditText)findViewById(R.id.et1);
        //建立Volley的請求隊列
        //在子線程
        requestQueue = Volley.newRequestQueue(this);
    }
    //Volley-GET
    public void bt_3(View v)
    {
        //1-啓動進度對話框
        final ProgressDialog pd = ProgressDialog.show(this,null,"請稍後……");

        //構建StringRequest
        StringRequest sr=new StringRequest("http://192.168.0.164:81/index.asp?name=Volley&password=456",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        //處理正常響應
                        //在主線程裏運行
                        et1.setText(s);
                        pd.dismiss();
                    }
                },
                new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                //處理異常響應
                pd.dismiss();
                Toast.makeText(JDKActivity.this, "響應異常   響應狀態碼"+volleyError.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
            }
        });
        //加入隊列
        requestQueue.add(sr);
    }
View Code

 

Volley-POSTide

 //Volley-POST
    public void bt_4(View v)
    {
        //1-啓動進度對話框
        final ProgressDialog pd = ProgressDialog.show(this,null,"請稍後……");

        //構建StringRequest
        StringRequest sr=new StringRequest(Request.Method.POST,"http://192.168.0.164:81/index.asp",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        //處理正常響應
                        //在主線程裏運行
                        et1.setText(s);
                        pd.dismiss();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //處理異常響應
                        pd.dismiss();
                        Toast.makeText(JDKActivity.this, "響應異常   響應狀態碼"+volleyError.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
                    }
                }){
            //重寫獲得參數的方法
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> rtn=new HashMap<>();
                rtn.put("name","postvolley");
                rtn.put("password","567");
                return rtn;
            }
        };
        //加入隊列
        requestQueue.add(sr);
    }
View Code

相關文章
相關標籤/搜索