dtsps00544 2018-03-08 08:22
浏览 51
已采纳

无法在laravel中解析jsonarray,使用volley库从android发送

This is volley request code in android app

String url = "http://xx.xx.xx.xx:80/api/attendances";  //this is address. replaced with xx here
JSONArray jsonArray = new JSONArray();
            for(int i=0; i < studentList.size(); i++)
            {
                jsonArray.put(studentList.get(i).toJson());
            }

            JSONObject parameters = new JSONObject();

            try {
                parameters.put("class_id", class_id);
                parameters.put("students", jsonArray);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                    url, parameters,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d("API", response.toString());

                            try {
                                if(response.getString("status").equalsIgnoreCase("Success")){

                                }
                                else {
                                    Toast.makeText(getBaseContext(), response.getString("msg"), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            pDialog.dismiss();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // hide the progress dialog
                            VolleyLog.d("API", "Error: " + error.toString());
                            Toast.makeText(getBaseContext(), "Unable to contact server.", Toast.LENGTH_LONG).show();
                            if(error.networkResponse.data!=null) {

                                VolleyLog.d("API", "Error: " + body);
                            }
                            pDialog.dismiss();
                        }

                    }){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");
                    headers.put("Authorization","Bearer "+ token);
                    return headers;
                }
            };

            AppController.getInstance().addToRequestQueue(jsonObjectRequest, tag_json_obj);

This produces jsonObjectRequest

{"class_id":"11","students":[{"id":"222","present":true},{"id":"223","present":true},{"id":"224","present":false}]}

Laravel code for this request is -

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'students' => 'required',
        'class_id' => 'required',
    ]);

    if ($validator->fails()) {
        return response()->json($validator->errors());
    }
    $user = auth()->user();

    if (Gate::allows('post_attendance')) {
        $attendance = Attendance::create([
            'cl_id' => $request->class_id,
            'user_id' => $user->id,
        ]);

        try {
            $students = json_decode($request->students);
            foreach ($students as $student) {
                Present::create([
                    'attendance_id' => $attendance->id,
                    'student_id' => $student->id,
                    'present' => $student->present
                ]);
            }
        } catch (\Exception $exception) {
            return response()->json(['error', $exception->getMessage()], 300);
        }

        return response()->json([
            'status' => 'Success',
            'msg' => 'Added'
        ]);
    }


    return response()->json([
        'status' => 'Error',
        'msg' => 'Access Denied!'
    ]);
}

If I use android app this code creates an entry in Attendance table but still gives error "BasicNetwork.performRequest: Unexpected response code 300 for http://XX.XX.XX.XX:80/api/attendances". So theres a problem in parsing JSONArray. If i comment out try catch part it runs successfully with status 'Success'.

Also if use API client same Laravel code works perfectly and creates entries in Attendance table as well as Present table.

enter image description here

In screenshot students field contains students jsonarray given below -

[{"id":"222","present":true},{"id":"223","present":true},{"id":"224","present":false}]

Problem is I have no idea why request sent from API client is working but but same request is not working on android client, Laravel code works perfectly with API client. But it does work with request sent from android.

I have searched a lot did not find any similar question or a way to debug android client. Volley gives only error response code. Is there any way to access whole error response given by Laravel? Any help appreciated

  • 写回答

1条回答 默认 最新

  • duandi8838 2018-03-08 08:25
    关注

    You are sending a json and you can get the json like

    try {
            $students = json_decode($request->getContent());
            foreach ($students['students'] as $student) {
                Present::create([
                    'attendance_id' => $attendance->id,
                    'student_id' => $student->id,
                    'present' => $student->present
                ]);
            }
        } catch (\Exception $exception) {
            return response()->json(['error', $exception->getMessage()], 300);
        }
    

    Use $request->getContents() to get the json

    Hope this helps

    It helped with these tweaks

    try {
            $data = json_decode($request->getContent(),true);
            $attendance = Attendance::create([
                'cl_id' => $data['class_id'],
                'user_id' => $user->id,
            ]);
                foreach ($data['students'] as $student) {
                    Present::create([
                        'attendance_id' => $attendance->id,
                        'student_id' => $student['id'],
                        'present' => $student['present']
                    ]);
                }
            } catch (\Exception $exception) {
                return response()->json(['error', $exception->getMessage()], 300);
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效