POST 请求 Json 文件传递​​字符串并等待响应 Volley [英] POST Request Json file passing String and wait for the response Volley

查看:29
本文介绍了POST 请求 Json 文件传递​​字符串并等待响应 Volley的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 和 Volley 的新手,我需要你的帮助.我需要发布一个字符串,有一个 json 来响应它,如果它没有提出错误的请求,则使用来自我的请求的一些值开始一个新的意图.

I am new to Android and Volley, and I need your help. I need to post a String, have a json to response to it and, if it doesn't raise a bad request, start a new intent with some values coming from my request.

这是我想要做的一个简单的模式:按登录按钮 -> 星标请求 -> 检查是否正常 -> 使用响应值启动新意图.

This is a simple schema of what I want to do: Press Login button -> star request -> check if it is ok -> start a new intent with response values.

我已经看到Volley使用异步方法进行查询.这是我的代码:

I have seen that Volley uses asynchronous method to query. Here's my code:

boolean temp=false;
     login.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                boolean temp=false;
                     if (!id.getText().toString().isEmpty() && !pw.getText().toString().isEmpty()) {
                        temp = verifyCredentials(v.getContext()); //Doesn't work because Volley is asynchronous.

                     if(temp==true)
                     {
                         Intent intentMain = new Intent(v.getContext(), MainActivity.class);//MainActivity.class);
                         intentMain.putExtra("username", id.getText().toString());
                         startActivityForResult(intentMain, 0);
                     }
                } else {//strighe vuote
                    //toast
                    Toast.makeText(v.getContext(), "Compila i campi", Toast.LENGTH_SHORT).show();
                }


            }
        });

public boolean verifyCredentials(Context context) {
        final boolean[] tempToReturn = {false};
        mTextView = (TextView) findViewById(R.id.textView2);
        RequestQueue queue = Volley.newRequestQueue(context);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, apiURL,
                new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                mTextView.setText("Response is:" + response.substring(500));
                tempToReturn[0] =true;
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String json = null;
                NetworkResponse response = error.networkResponse;
                if(response != null && response.data != null){
                    switch(response.statusCode){
                        case 400:
                            json = new String(response.data);
                            json = trimMessage(json, "message");
                            if(json != null) displayMessage(json);
                            break;
                    }
                    //Additional cases
                }
                mTextView.setText("Error bad request");
            }
            public String trimMessage(String json, String key){
                String trimmedString = null;

                try{
                    JSONObject obj = new JSONObject(json);
                    trimmedString = obj.getString(key);
                } catch(JSONException e){
                    e.printStackTrace();
                    return null;
                }

                return trimmedString;
            }

            //Somewhere that has access to a context
            public void displayMessage(String toastString){
                mTextView.setText("Response is:" +toastString);
            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                AuthenticationUserName = id.getText().toString();
                AuthenticationPassword = pw.getText().toString();
                params.put("grant_type", Authenticationgrant_type);
                params.put("username", AuthenticationUserName);
                params.put("password", AuthenticationPassword);
                return params;
            }
        };
        queue.add(stringRequest);
        return  tempToReturn[0];
    }

我正在使用 Volley,因为我的 gradle 是 23,而且我的 API 级别也是如此,所以我无法使用 apache 包.

I am using Volley because my gradle's is the 23 and my APi level too so I can't use the apache package.

新代码:

 public void onClick(View v) {
                boolean temp = true;
                if (!id.getText().toString().isEmpty() && !pw.getText().toString().isEmpty()) {

                    myContext = v.getContext();
                    VolleyResponseListener listener = new VolleyResponseListener() {
                        @Override
                        public void onError(VolleyError error) {
                            String json = null;
                            NetworkResponse response = error.networkResponse;
                            if(response != null && response.data != null){
                                switch(response.statusCode){
                                    case 400:
                                        json = new String(response.data);
                                        json = trimMessage(json, "message");
                                        if(json != null) displayMessage(json);
                                        break;
                                }
                                //Additional cases
                            }
                            mTextView.setText("Error bad request");
                        }
                        @Override
                        public void onResponse(JSONObject  response) {
                            try {
                                fullName = response.getString("fullName");
                                token= response.getString("access_token");
                                expirationDate=response.getString(".expires");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            mTextView.setText("Response is:" + fullName+token+expirationDate);
                            Intent intentMain = new Intent(myContext, MainActivity.class);//MainActivity.class);
                            intentMain.putExtra("username", id.getText().toString());
                            startActivityForResult(intentMain, 0);
                        }

                        public String trimMessage(String json, String key){
                            String trimmedString = null;
                            try{
                                JSONObject obj = new JSONObject(json);
                                trimmedString = obj.getString(key);
                            } catch(JSONException e){
                                e.printStackTrace();
                                return null;
                            }

                            return trimmedString;
                        }

                        //Somewhere that has access to a context
                        public void displayMessage(String toastString){
                            //Toast.makeText(MainActivity.this, toastString, Toast.LENGTH_LONG).show();
                            mTextView.setText("Response is:" +toastString);
                        }
                    };

                    verifyCredentials(myContext,listener);

我已经创建了这个界面:

and I have create this interface:

public interface VolleyResponseListener {
    void onError(VolleyError error);
    void onResponse(JSONObject  response);
}

这是我的验证凭证的新代码:

And here is the new code of my verifycredential:

   public boolean verifyCredentials(Context context,final VolleyResponseListener listener) {
        final boolean[] tempToReturn = {false};
        mTextView = (TextView) findViewById(R.id.textView2);
        Map<String,String> params = new HashMap<String, String>();
        AuthenticationUserName = id.getText().toString();
        AuthenticationPassword = pw.getText().toString();
                    //key value
        params.put("grant_type", Authenticationgrant_type);
        params.put("username",  AuthenticationUserName);
    params.put("password", AuthenticationPassword);

    RequestQueue queue = Volley.newRequestQueue(context);

    SimpleRequest jsObjRequest  = new SimpleRequest(Request.Method.POST, apiURL,
            params,new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject  response) {
                    listener.onResponse(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onError(error);
        }
        }
    });
    queue.add(jsObjRequest);
    return  tempToReturn[0];
}

推荐答案

我已经回答了一些与您的问题类似的问题,例如:

I have answered some questions that look like your issue, such as:

Android:如何从方法返回异步 JSONObject使用 Volley?

你不应该等待那个布尔返回值.相反,您可以尝试以下方式(当然,您可以将 JSONArray 请求替换为 JSONObjectString 请求):

You should not wait for that boolean return value. Instead, you can try the following way (of course, you can replace JSONArray request by JSONObject or String request):

VolleyResponseListener listener = new VolleyResponseListener() {
            @Override
            public void onError(String message) {
                // do something...
            }

            @Override
            public void onResponse(Object response) {
                // do something...
            }
        };

makeJsonArrayRequest(context, Request.Method.POST, url, requestBody, listener);

makeJsonArrayRequest 的主体可以如下:

    public void makeJsonArrayRequest(Context context, int method, String url, String requestBody, final VolleyResponseListener listener) {
        JSONObject jsonRequest = null;        
        try {
            ...
            if (requestBody != null) {
                jsonRequest = new JSONObject(requestBody);
            }
            ...
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                listener.onResponse(jsonArray);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error.toString());
            }
        });

        // Access the RequestQueue through singleton class.
        MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
    }

VolleyResponseListener 接口如下:

public interface VolleyResponseListener {
    void onError(String message);

    void onResponse(Object response);
}

对于您在下面的评论:

首先是:方法的顺序",例如在我的情况下,按下按钮后,我必须调用哪个方法?

假设我们在 onCreate 中:您可以先创建VolleyResponseListener listener,然后在按下按钮时调用verifyCredentials(..., listener);.

Let's assume we are inside onCreate: You can create VolleyResponseListener listener first, then call verifyCredentials(..., listener); when pressing the button.

我可以在哪里调用意图?

这将在上述VolleyResponseListener listeneronResponse内调用(当然,在里面你可以根据你的要求检查更多的条件)

This will be called inside onResponse of the above VolleyResponseListener listener (of course, inside that you can check more conditions depend on your requirements)

第二:我必须发送一个字符串,但我想要一个 jsonArrayRespond,在那里是一种方法吗?或者它只适用于 2 种参数,例如字符串请求/字符串发送和json请求/json发送?

根据 Google 的培训文档:

  • StringRequest:指定一个 URL 并接收原始字符串作为响应.
  • ImageRequest:指定一个 URL 并接收响应图像.
  • JsonObjectRequest 和 JsonArrayRequest(都是JsonRequest):指定一个 URL 并获取一个 JSON 对象数组(分别)回应.
  • StringRequest: Specify a URL and receive a raw string in response.
  • ImageRequest: Specify a URL and receive an image in response.
  • JsonObjectRequest and JsonArrayRequest (both subclasses of JsonRequest): Specify a URL and get a JSON object or array (respectively) in response.

当然,对于没有开箱即用的 Volley 支持的类型,您可以实现自己的自定义请求类型.查看实施自定义请求.

And of course you can implement your own custom request types, for types that don't have out-of-the-box Volley support. Take a look at Implementing a Custom Request.

希望这有帮助!

这篇关于POST 请求 Json 文件传递​​字符串并等待响应 Volley的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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