POST请求Json文件传递String并等待响应Volley

时间:2015-09-17 09:38:43

标签: android json android-studio android-volley

我是Android和Volley的新手,我需要你的帮助。 我需要发布一个String,有一个json来响应它,如果它没有引发一个错误的请求,请启动一个新的intent,其中包含来自我的请求的一些值。

这是我想要做的简单架构: 按登录按钮 - >明星请求 - >检查一下是否正常 - >用响应值开始一个新的意图。

我看到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);
}

这是我的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];
}

1 个答案:

答案 0 :(得分:1)

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

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

您不应该等待该布尔返回值。相反,您可以尝试以下方式(当然,您可以通过JSONArrayJSONObject请求替换String请求):

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

  

我可以在哪里调用意图?

这将在上述onResponse的{​​{1}}内进行调用(当然,您可以根据自己的要求检查更多条件)

  

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

根据Google's training documentation

  • StringRequest:指定一个URL并接收响应中的原始字符串
  • ImageRequest:指定一个网址并接收一张图片作为回复
  • JsonObjectRequest和JsonArrayRequest(两个子类) JsonRequest):指定一个URL并获取 JSON对象数组 (分别)作为回应

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

希望这有帮助!