如何在此android studio代码中发送POST参数 [英] How to I send POST parameters in this android studio code

查看:327
本文介绍了如何在此android studio代码中发送POST参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android的新手,现在开始学习它.我正在开发一个能够成功获取来自get请求的响应的应用程序.现在,我想用一个参数执行POST请求,这是我到目前为止提出的:

I'm new to android and learning it now. I'm working on an application where I was able to get response form a get request successfully. Now I want to execute a POST request with a single parameter this is what I've came up with so far:

public class BGTask extends AsyncTask<String, String, String > {

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String color = "null";

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            //I want to pass the id parameter
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line ="";
            while ((line = reader.readLine()) != null){
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            int status = parentObject.getInt("status");


            if(status == 1) {
                color = parentObject.getString("bgcolor");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {

            if(connection != null) {
                    connection.disconnect();
                }
                try {
                    if(reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return color;
    }
}

可变颜色为十六进制代码,即#FF0089

The variable color is in hex code i.e #FF0089

推荐答案

**对GET,POST和网络调用使用凌空库,非常简单有效**

** Use volley library for GET , POST and network calls it's very simple and efficient **

首先创建AppController.java

First create AppController.java

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
        ConnectivityReceiver.connectivityReceiverListener = listener;
    }
} 

第二次发出POST请求

Second make POST request

public void Send() {
        final String First = "";
        final String Second = "";


        StringRequest stringRequest = new StringRequest(Request.Method.POST, CREATEORDER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("RESPONSE", response);

                        JSONObject jObj = null;
                        try {
                            jObj = new JSONObject(response);
                            String success = jObj.getString("success");
                            String errorMessage = jObj.getString("message");

                            if (success.equals("")) {

                                Intent intent = new Intent(SendGiftActivity.this, PayScreenActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(SendGiftActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //  Toast.makeText(SignUpActivity.this, response, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(SendGiftActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_FIRST_PARAMETERS, First);
                params.put(KEY_SECOND_PARAMETER, Second);


                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

包括排球库

Include volley library

 compile 'com.android.volley:volley:1.0.0'

别忘了在清单文件的应用程序标记中添加android:name=".AppController"

这篇关于如何在此android studio代码中发送POST参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆