当前位置: 首页 > 面试题库 >

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

井镜
2023-03-14
问题内容

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

问题答案:

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

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

您不应该等待该布尔值返回。相反,你可以试试下面的方法(当然,你可以替换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);
}

对于下面的评论:

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

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

在哪里可以调用意图?

这将onResponse在上述内部被调用VolleyResponseListener listener(当然,在内部可以根据您的要求检查更多条件)

第二:我必须发送一个String,但是我想要一个jsonArrayRespond,有没有一种方法可以做到这一点?
或者它仅适用于2种参数,例如字符串请求/字符串发送和json请求/ json发送?

根据Google的培训文档:

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

当然,对于不具有即用Volley支持的类型,您可以实现自己的自定义请求类型。看一下实现自定义请求。

希望这可以帮助!



 类似资料:
  • 我已经创建了一个简单的Jersey客户端,它能够成功地使用有效负载执行POST请求。但现在它正在等待来自httpendpoint的响应: 问:代码是否有可能不等待响应。 我试图阅读泽西客户端文档,以确定我的代码是否有可能不等待响应?我看到我们只能在读取响应后关闭连接,但在我的情况下没有用。我想在将有效负载发布到endpoint后立即关闭连接。 我只需要触发并忘记POST请求,因为我不关心响应。这是

  • 是否可以在不等待响应的情况下发送HTTP请求? 我在做一个物联网项目,需要记录传感器的数据。在每一个设置中,都有许多传感器,一个中央协调器(主要由Raspberry Pi实现)从传感器收集数据,并通过Internet将数据发送到服务器。 提前感谢! 编辑:传感器是无线的,但他们使用的技术在发送到协调器时很少(或没有)延迟。此协调器必须通过Internet发送数据。但是,假设互联网连接不好。因为这将

  • 问题内容: 我正在尝试使用 nodejs 和 请求 [2] 向google QPX Express API [1]发出HTTP POST请求。 我的代码如下: 我想做的是使用multipart参数[3]传递JSON。但是我没有正确的JSON响应,而是收到一个错误(未定义400)。 当我使用CURL使用相同的JSON和API密钥发出请求时,它工作正常。因此,我的API密钥或JSON没错。 我的代码有

  • 我在spring mvc 3.2.2中使用apache http客户端同步发送5个get请求,如图所示。 如何异步(并行)发送所有这些内容并等待请求返回,以便从所有 GET 请求返回已解析的有效负载字符串?

  • 这是我第一次使用剧作家,我不知道如何等待请求和验证响应。我已经使用cypress很长时间了,管理网络请求非常容易。例如,我需要在单击按钮后验证响应,这就是我使用cypress的方法: 这就是我试图对剧作家做同样的事情的方式,但是它验证了早在点击保存按钮之前就发送的请求。我不知道如何正确管理这个请求,这是我的测试套件的一个停止: 任何帮助或建议都将不胜感激

  • 问题内容: PHP会以1-2秒的延迟返回值jQuery.post不等待响应。 您如何看待,是否有可能解决该问题并等待响应? 注意 与get相同的功能效果很好 问题答案: $ .post是异步的,您需要使用$ .ajax并将async设置为false,这样您就可以等待响应。您可以在此处了解更多信息: http //api.jquery.com/jQuery.ajax/