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

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

问题描述

我是新来的Andr​​oid和截击,我需要你的帮助。 我要发布一个字符串,有一个JSON来应对它,如果它不提出无效请求,开始一个新的意图与一些值从我的要求来了。

这是我想要做一个简单的模式: preSS登录按钮 - >星的要求 - >检查,如果它是确定 - >开始一个新的意图与响应值

我已经看到了排球用于查询异步方法。 这是我的code:

 布尔TEMP = FALSE;
     login.setOnClickListener(新View.OnClickListener(){
                公共无效的onClick(视图v){
                布尔TEMP = FALSE;
                     如果(id.getText()的toString()的isEmpty()及!。&安培;!pw.getText()的toString()的isEmpty()。){
                        临时=的verifyCredentials(v.getContext()); //不起作用,因为排球是异步的。

                     如果(临时==真)
                     {
                         意图int​​entMain =新的意图(v.getContext(),MainActivity.class); // MainActivity.class);
                         intentMain.putExtra(用户名,id.getText()的toString());
                         startActivityForResult(intentMain,0);
                     }
                }其他{// strighe vuote
                    //敬酒
                    Toast.makeText(v.getContext(),我Compila坎皮萨伦蒂,Toast.LENGTH_SHORT).show();
                }


            }
        });

公共布尔的verifyCredentials(上下文的背景下){
        最终布尔[] tempToReturn = {假};
        mTextView =(TextView中)findViewById(R.id.textView2);
        请求队列排队= Volley.newRequestQueue(上下文);

        StringRequest stringRequest =新StringRequest(Request.Method.POST,apiURL,
                新Response.Listener<字符串>(){
            @覆盖
            公共无效onResponse(字符串响应){
                mTextView.setText(回应是:+ response.substring(500));
                tempToReturn [0] =真;
            }
        },新Response.ErrorListener(){
            @覆盖
            公共无效onErrorResponse(VolleyError错误){
                JSON字符串= NULL;
                NetworkResponse响应= error.networkResponse;
                如果(响应=零和放大器;!&安培;!response.data = NULL){
                    开关(response.status code){
                        案例400:
                            JSON =新的String(response.data);
                            JSON = trimMessage(JSON,信息);
                            如果(JSON!= NULL)displayMessage(JSON);
                            打破;
                    }
                    //其他情况下,
                }
                mTextView.setText(错误错误的请求);
            }
            公共字符串trimMessage(JSON字符串,字符串键){
                字符串trimmedString = NULL;

                尝试{
                    JSONObject的OBJ =新的JSONObject(JSON);
                    trimmedString = obj.getString(密钥);
                }赶上(JSONException E){
                    e.printStackTrace();
                    返回null;
                }

                返回trimmedString;
            }

            //地方,访问上下文
            公共无效displayMessage(字符串toastString){
                mTextView.setText(回应是:+ toastString);
            }
        }){
            @覆盖
            保护地图<字符串,字符串> getParams()方法{
                地图<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();
                。AuthenticationUserName = id.getText()的toString();
                AuthenticationPassword = pw.getText()的toString()。
                params.put(grant_type,Authenticationgrant_type);
                params.put(用户名,AuthenticationUserName);
                params.put(密码,AuthenticationPassword);
                返回PARAMS;
            }
        };
        queue.add(stringRequest);
        返回tempToReturn [0];
    }
 

我使用的排球,因为我的摇篮的是23,我的API级别太,所以我不能使用Apache包。

编辑:新的code:

 公共无效的onClick(视图v){
                布尔温度= TRUE;
                如果(id.getText()的toString()的isEmpty()及!。&安培;!pw.getText()的toString()的isEmpty()。){

                    myContext = v.getContext();
                    VolleyResponseListener监听器=新VolleyResponseListener(){
                        @覆盖
                        公共无效onerror的(VolleyError错误){
                            JSON字符串= NULL;
                            NetworkResponse响应= error.networkResponse;
                            如果(响应=零和放大器;!&安培;!response.data = NULL){
                                开关(response.status code){
                                    案例400:
                                        JSON =新的String(response.data);
                                        JSON = trimMessage(JSON,信息);
                                        如果(JSON!= NULL)displayMessage(JSON);
                                        打破;
                                }
                                //其他情况下,
                            }
                            mTextView.setText(错误错误的请求);
                        }
                        @覆盖
                        公共无效onResponse(JSONObject的响应){
                            尝试 {
                                全名= response.getString(全名);
                                令牌= response.getString(access_token);
                                EXPIRATIONDATE = response.getString(过期);
                            }赶上(JSONException E){
                                e.printStackTrace();
                            }
                            mTextView.setText(回应是:+全名+令牌+ EXPIRATIONDATE);
                            意图int​​entMain =新的意图(myContext,MainActivity.class); // MainActivity.class);
                            intentMain.putExtra(用户名,id.getText()的toString());
                            startActivityForResult(intentMain,0);
                        }

                        公共字符串trimMessage(JSON字符串,字符串键){
                            字符串trimmedString = NULL;
                            尝试{
                                JSONObject的OBJ =新的JSONObject(JSON);
                                trimmedString = obj.getString(密钥);
                            }赶上(JSONException E){
                                e.printStackTrace();
                                返回null;
                            }

                            返回trimmedString;
                        }

                        //地方,访问上下文
                        公共无效displayMessage(字符串toastString){
                            //Toast.makeText(MainActivity.this,toastString,Toast.LENGTH_LONG).show();
                            mTextView.setText(回应是:+ toastString);
                        }
                    };

                    的verifyCredentials(myContext,监听器);
 

和我创建这个接口:

 公共接口VolleyResponseListener {
    无效的onError(VolleyError错误);
    无效onResponse(JSONObject的反应);
}
 

这里是我verifycredential新的code:

 公共布尔的verifyCredentials(上下文的背景下,最终VolleyResponseListener监听器){
        最终布尔[] tempToReturn = {假};
        mTextView =(TextView中)findViewById(R.id.textView2);
        地图<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();
        。AuthenticationUserName = id.getText()的toString();
        AuthenticationPassword = pw.getText()的toString()。
                    //键值
        params.put(grant_type,Authenticationgrant_type);
        params.put(用户名,AuthenticationUserName);
    params.put(密码,AuthenticationPassword);

    请求队列排队= Volley.newRequestQueue(上下文);

    SimpleRequest jsObjRequest =新SimpleRequest(Request.Method.POST,apiURL,
            PARAMS,新Response.Listener<的JSONObject>(){
                @覆盖
                公共无效onResponse(JSONObject的响应){
                    listener.onResponse(响应);
                }
            },新Response.ErrorListener(){
        @覆盖
        公共无效onErrorResponse(VolleyError错误){
            listener.onError(错误);
        }
        }
    });
    queue.add(jsObjRequest);
    返回tempToReturn [0];
}
 

解决方案

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

<一个href="http://stackoverflow.com/questions/32375295/android-how-to-return-async-jsonobject-from-method-using-volley">Android:如何从使用方法凌空返回异步的JSONObject?

您应该等不到那布尔返回值。相反,你可以试试下面的方法(当然,你可以通过的JSONObject 或<$ C $替换 JSONArray 请求C>字符串要求):

  VolleyResponseListener监听器=新VolleyResponseListener(){
            @覆盖
            公共无效onerror的(字符串消息){
                // 做一点事...
            }

            @覆盖
            公共无效onResponse(对象响应){
                // 做一点事...
            }
        };

makeJsonArrayRequest(背景下,Request.Method.POST,网址,requestBody,监听器);
 

正文 makeJsonArrayRequest 可以是如下:

 公共无效makeJsonArrayRequest(上下文的背景下,诠释方法,URL字符串,字符串requestBody,最终VolleyResponseListener监听器){
        JSONObject的jsonRequest = NULL;
        尝试 {
            ...
            如果(requestBody!= NULL){
                jsonRequest =新的JSONObject(requestBody);
            }
            ...
        }赶上(JSONException E){
            e.printStackTrace();
        }

        JsonArrayRequest jsonArrayRequest =新JsonArrayRequest(方法,URL,jsonRequest,新Response.Listener&LT; JSONArray&GT;(){
            @覆盖
            公共无效onResponse(JSONArray JSONArray),其中{
                listener.onResponse(JSONArray),其中,
            }
        },新Response.ErrorListener(){
            @覆盖
            公共无效onErrorResponse(VolleyError错误){
                listener.onError(error.toString());
            }
        });

        //访问请求队列通过单例类。
        MySingleton.getInstance(上下文).addToRequestQueue(jsonArrayRequest);
    }
 

VolleyResponseListener 界面如下:

 公共接口VolleyResponseListener {
    无效的onError(字符串消息);

    无效onResponse(对象响应);
}
 

对于低于您的意见:

  

首先是:该方法的秩序,例如,在我的情况下,   经过pressing按钮,我必须调用哪个方法?

让我们假设我们都在里面的onCreate : 您可以创建 VolleyResponseListener监听器第一,然后调用的verifyCredentials(...,监听器); 时pressing的按钮。

  

在哪里我可以打电话的意图?

这将在 onResponse 被称为上述 VolleyResponseListener监听器(当然里面,你可以查看更多条件取决于您的要求)

  

二:我要发送一个字符串,但我希望有一个jsonArrayRespond,有   是一种方法来做到这一点?或用2种参数,例如,只有工作   串请求/发送字符串和JSON请求/ JSON发送?

根据谷歌的培训文档

  • StringRequest:指定URL和接收的一个原始字符串响应
  • ImageRequest:指定URL和接收图像响应
  • JsonObjectRequest和JsonArrayRequest(两个子类 JsonRequest):指定一个URL,并获得 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.

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

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

EDIT: NEW CODE:

 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: How to return async JSONObject from method using Volley?

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

Body of makeJsonArrayRequest can be as the following:

    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 interface as the following:

public interface VolleyResponseListener {
    void onError(String message);

    void onResponse(Object response);
}

For your comments below:

first of all is: the "order" of the method, for example in my case, After pressing button, which method I have to call?

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

And where I can call the intent?

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

Second: I have to send a String but I want a jsonArrayRespond, there is a method to do this? Or it work only with 2 kind of parameter such string request/string sent and json request/json sent?

According to Google's training documentation:

  • 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.

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.

Hope this helps!

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

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