【问题标题】:POST Request Json file passing String and wait for the response VolleyPOST 请求 Json 文件传递​​字符串并等待响应 Volley
【发布时间】:2015-12-14 03:09:22
【问题描述】:

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

这是我想要做的简单架构: 按登录按钮 -> 星请求 -> 检查是否正常 -> 使用响应值启动新意图。

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

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 包。

编辑:新代码:

 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);

我已经创建了这个界面:

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

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

   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];
}

【问题讨论】:

  • 之前只显示一个进度对话框,当请求完成时volley会自动调用回调响应或错误
  • @MamataGelanee 这个网址是我的个人Api,我不会分享它....对不起
  • @SacreDeveloper 你能给我发一些示例代码吗?谢谢
  • 看看下面的@BNK答案,它应该对你有帮助:)

标签: android json android-studio android-volley


【解决方案1】:

我已经回答了一些看起来像您的问题的问题,例如:

Android: How to return async JSONObject from method using Volley?

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

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);
}

以下为您的 cmets:

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

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

我可以在哪里调用意图?

上面的VolleyResponseListener listener里面的onResponse里面会调用这个(当然里面可以根据自己的需求查看更多的条件)

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

根据Google's training documentation

  • StringRequest:指定一个 URL 并接收 一个原始字符串作为响应
  • ImageRequest:指定一个 URL 并接收 响应的图像
  • JsonObjectRequest 和 JsonArrayRequest(都是 JsonRequest):指定一个 URL 并获取一个 JSON 对象array (分别)回应

当然,对于没有开箱即用 Volley 支持的类型,您可以实现自己的自定义请求类型。看看Implementing a Custom Request

希望这会有所帮助!

【讨论】:

  • 感谢您的回答。很多“愚蠢”的东西我都不懂,首先是:方法的“顺序”,比如我的情况,按下按钮后,我要调用哪个方法?以及在哪里可以调用意图?第二:我必须发送一个字符串,但我想要一个 jsonArrayRespond,有办法做到这一点吗?或者它仅适用于 2 种参数,例如发送的字符串请求/字符串和发送的 json 请求/json?谢谢
  • 谢谢你的回复;我试着做你写的,但它不起作用......。我按下按钮后应用程序崩溃,我看到了调试模式问题出在它执行了verycredential函数之后,因为它什么都不做。我已经修改了代码。我现在必须改变/做什么?谢谢
  • java.lang.NullPointerException: at myproject.LoginActivity$1$1.onError(LoginActivity.java:112)->mTextView.setText("Error bad request");在 myproject.LoginActivity$3.onErrorResponse(LoginActivity.java:220)-> listener.onError(error);在 com.android.volley.Request.deliverError(Request.java:563) 在 com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101) 在 android.os.Handler.handleCallback(Handler.java:808 ) 在 android.os.Handler.dispatchMessage(Handler.java:103) ....
  • 检查你的mTextView是否为空
  • 我已经把 mTextView = (TextView) findViewById(R.id.textView2);在 mTextView.setText 之前,现在它可以工作了。非常感谢您的帮助! =)
猜你喜欢
  • 1970-01-01
  • 2011-01-12
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2022-01-10
  • 2018-05-27
  • 2014-11-30
相关资源
最近更新 更多