繁体   English   中英

排球POST请求android

[英]Volley POST request android

我不确定我应该使用哪种类型的内容发布到api,因为我对这个发展中国家很陌生。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        button = (Button)findViewById(R.id.reg_btn_sign_up);
        btnCancel = (Button)findViewById(R.id.reg_button_cancel);
        Email = (EditText)findViewById(R.id.reg_email);
        Name = (EditText)findViewById(R.id.reg_name);
        Pass = (EditText)findViewById(R.id.reg_pass);
        ConPass = (EditText)findViewById(R.id.reg_confirm_pass);


    button.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            email = Email.getText().toString();
            name = Name.getText().toString();
            password = Pass.getText().toString();
            conPass = ConPass.getText().toString();

            JSONObject jsonBody = new JSONObject();
            try {
                jsonBody.put("username", email);
                jsonBody.put("password", password);
                jsonBody.put("name", name);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            final String mRequestBody = jsonBody.toString();


            StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject = jsonArray.getJSONObject(0);
                        String status = jsonObject.getString("status");
                        String result = jsonObject.getString("result");
                        builder.setTitle("Server Response...");
                        builder.setMessage(result);
                    } catch (JSONException e){
                            e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            })

            {
                @Override
                public byte[] getBody() throws AuthFailureError {

                    try {
                        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        return null;
                    }

                }


                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }
            };

            MySingleton.getmInstance(RegisterActivity.this).addRequestQueue(stringRequest);

        }
    });

}

}

这是我在logcat中获得的日志:

W / System.err:org.json.JSONException:无法将类型为org.json.JSONObject的值{“ status”:0,“ result”:“访问受限”}转换为JSONArray

我在POSTMAN中正确执行了操作,但是在android中无法获得想要的结果。

在命令中添加了API。

尝试这个

  public void login(final String user, final String pass) {
        Log.e("Constant.KEY_URL", String.valueOf(Constant.KEY_URL));
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.KEY_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                     //you will get your response in log
                        Log.e("response", response);

                        if (user.equals("") || pass.equals("")) {

                            Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
                        } else if (!response.equals("empty")) {
                            Log.e("isempty", "yes");

                            try {
                                JSONArray array = new JSONArray(response);
                                for (int i = 0; i < array.length(); i++) {
                                    JSONArray array1 = array.getJSONObject(i).getJSONArray("data");
                                    for (int j = 0; j < array1.length(); j++) {


                                        startActivity(intent);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            Log.e("isempty", "else");
                            Toast.makeText(getApplicationContext(), "Username or password is incorrect", Toast.LENGTH_LONG).show();
                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
                        //  Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
                        Log.e("Error", "msg==>" + error);
                    }
                }) {

            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> reqMap = new LinkedHashMap<>();
                reqMap.put("username", user);
                reqMap.put("password", pass);
                reqMap.put("method", "login");

                Log.e("request","login" + reqMap);

                return reqMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 30, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        requestQueue.add(stringRequest);
        stringRequest.setTag("TAG");

    }

在您的按钮单击事件上调用此登录方法

    btnlogin.setOnClickListener(new View.OnClickListener()

    {
        @Override
        public void onClick(View view) {
            user = editusername.getText().toString().trim();
            pass = editpassword.getText().toString().trim();

           login(user, pass);
        }

    });

我假设您正在使用截击请求响应来执行注册功能。.有关我用于登录目的的代码,您可以根据需要进行更改。

您得到的响应是JSONObject而不是JSONArray

尝试在onResponse方法中使用以下代码:

try {
                    JSONObject jsonObject = new JSONObject (response);
                    String status = jsonObject.getString("status");
                    String result = jsonObject.getString("result");
                    builder.setTitle("Server Response...");
                    builder.setMessage(result);
                } catch (JSONException e){
                        e.printStackTrace();
                }

您正在尝试从响应中解析一个数组,但是您正在获取JSONObject。 因此,当您获得响应时,请首先更改此行

JSONObject jsonObject = new JSONObject(response);

并检查状态

if(jsonObject.getString("status").equalsIgnoreCase("0")){
   // show error message or whatever
}else if(jsonObject.getString("status").equalsIgnoreCase("1")){
   // then parse your array if response has it
}

用这个

JSONObject jsonObject = new JSONObject (response.toString());

代替

JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM