Запрос залпа с заголовками и параметрами тела - PullRequest
0 голосов
/ 03 февраля 2019

Мне нужно сделать запрос API, который.

Два заголовка:

  1. Принять

  2. Авторизация

Пять параметров тела.

  1. Номер
  2. Марка
  3. Модель
  4. Описание
  5. Тарелки

Через почтальонавсе отлично работаетНо когда я пробую через приложение для Android, я не могу пройти.Примечание: вход через тот же хост работает отлично, так что настройка не проблема, я думаю, что моя основная проблема в вызове API.

public void add(View view) {
        RequestQueue queue = Volley.newRequestQueue(this);
        String URL = "http://10.0.2.2:8000/api/trucks";
        StringRequest request = new StringRequest(Request.Method.POST, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObj = new JSONObject(response);
                            // parse response
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        NetworkResponse response = error.networkResponse;
                        String errorMsg = "";
                        if (response != null && response.data != null) {
                            String errorString = new String(response.data);
                        }
                    }
                }
        ) {

            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Accept", "application/json");
                headers.put("Authorization", "Bearer " + myToken);
                return headers;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                TextInputEditText number = findViewById(R.id.textInputEditTextNumber);
                TextInputEditText make = findViewById(R.id.textInputEditTextMake);
                TextInputEditText model = findViewById(R.id.textInputEditTextModel);
                TextInputEditText description = findViewById(R.id.textInputEditTextDescription);
                TextInputEditText plates = findViewById(R.id.textInputEditTextPlates);

                params.put("number", number.getText().toString());
                params.put("make", make.getText().toString());
                params.put("model", model.getText().toString());
                params.put("description", description.getText().toString());
                params.put("plates", plates.getText().toString());
                return params;
            }
        };
        queue.add(request);
    }

Редактировать: решением # 1.

public void add(View view) throws JSONException {
    RequestQueue queue = Volley.newRequestQueue(this);
    TextInputEditText number = findViewById(R.id.textInputEditTextNumber);
    TextInputEditText make = findViewById(R.id.textInputEditTextMake);
    TextInputEditText model = findViewById(R.id.textInputEditTextModel);
    TextInputEditText description = findViewById(R.id.textInputEditTextDescription);
    TextInputEditText plates = findViewById(R.id.textInputEditTextPlates);

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("Number", number.getText().toString());
    jsonObject.put("Make", make.getText().toString());
    jsonObject.put("Model", model.getText().toString());
    jsonObject.put("Description", description.getText().toString());
    jsonObject.put("Plates", plates.getText().toString());
    final String requestBody = jsonObject.toString();

    JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, "http://10.0.2.2:8000/api/trucks", jsonObject,
            new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            //now handle the response
            Toast.makeText(truck_add.this, response.toString(), Toast.LENGTH_SHORT).show();

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            //handle the error
            Toast.makeText(truck_add.this, "An error occurred", Toast.LENGTH_SHORT).show();
            error.printStackTrace();
        }
    }) {    //this is the part, that adds the header to the request
        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Accept", "application/json");
            params.put("Authorization", myToken);
            return params;
        }
    };
    queue.add(jsonRequest);
}

Почтальон: Postman example

Ответы [ 2 ]

0 голосов
/ 03 февраля 2019
public void add(View view) throws JSONException {
   String URL = "http://10.0.2.2:8000/api/trucks";

   //removed views initialization from here.  
//you need to initialize views in oncreate() / oncreateView() method.  
/*first create json object in here.
then set keys as per required body format with values
*/
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("Number", number.getText().toString());
    jsonObject.put("Make", make.getText().toString());
    jsonObject.put("Model", model.getText().toString());
    jsonObject.put("Description", description.getText().toString());
    jsonObject.put("Plates", plates.getText().toString());
    final String requestBody = jsonObject.toString();

 RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest request = new StringRequest(Request.Method.POST, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObj = new JSONObject(response);
                        // parse response
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    NetworkResponse response = error.networkResponse;
                    String errorMsg = "";
                    if (response != null && response.data != null) {
                        String errorString = new String(response.data);
                    }
                }
            }
    )  {    //this is the part, that adds the header to the request
//this is where you need to add the body related methods
@Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return requestBody == null ? null : requestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s 
using %s", requestBody, "utf-8");
            return null;
        } 
        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json");
            params.put("Authorization", myToken);
            return params;
        }
    };
    queue.add(jsonRequest);
}  

Поставьте Log в каждом методе, чтобы проверить, какой метод выполняется и на возможную ошибку
Если после этого возникнет ошибка, отправьте сообщение об ошибке в logcat, и мы быстро ее исправим.

0 голосов
/ 03 февраля 2019

Если вы хотите передать данные через тело, вам нужно создать объект json перед запросом строки.
попробуйте этот способ,
1. создайте строковый URL для запроса.
2. createJSON объект для тела данных и передачи данных к нему.Мол,

JSONObject jsonObject= new JSONObject();  
jsonObject.put("Number", address.getNumber());  
jsonObject.put("Make", address.getMake());  
jsonObject.put("Model", address.getModel());  
jsonObject.put("Description", address.getDescription());  
jsonObject.put("Plates", address.getPlates());  
final String requestBody=jsonObject.toString();  

3.После этого примените stringRequest.
4. Теперь добавьте строки ниже перед методом заголовка и после метода ошибки.

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

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }  

5.В вашем методе getHeaders () используйте Content-Type для «application / json», а для авторизации вы должны использовать только токен без (Bearer).
Done.

...