简体   繁体   English

带标头和正文参数的排球请求

[英]Volley request with headers and body params

I need to make an api request which. 我需要发出一个api请求。

Two headers : 两个标题:

  1. Accept 接受

  2. Authorization 授权

Five body params. 五种身体参数。

  1. Number
  2. Make 使
  3. Model 模型
  4. Description 描述
  5. Plates

Through postman everything works great. 通过邮递员,一切都很好。 But when i try through android app i can't get through. 但是,当我尝试通过android应用程序时,我无法通过。 Note: Login through the same host works great so the setup its not the problem i think my main problem is in api call. 注意:通过同一主机登录非常有效,因此设置不是问题,我认为我的主要问题是在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);
    }

Edit: by Solution #1. 编辑:通过解决方案#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 : 邮递员: 邮递员的例子

When you want to pass the data through the body, you need to create a json object before string request. 当您想通过主体传递数据时,需要在字符串请求之前创建一个json对象。
try this way, 尝试这种方式
1. create a string url for request. 1.创建一个用于请求的字符串URL。
2. create json object for body data and pass data to it. 2.为主体数据创建json对象,并将数据传递给它。 Like, 喜欢,

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. After this, apply stringRequest. 3.之后,应用stringRequest。
4. Now, add below lines before header method and after error method. 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. In your getHeaders() method, use Content-Type for "application/json" and for Authorization you must use only token without (Bearer). 5.在您的getHeaders()方法中,将Content-Type用于“ application / json”,对于Authorization,您必须仅使用令牌而不使用(Bearer)。
Done. 完成。

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

Put Log in every method to check which method being executed and for possible error 将Log放入每个方法中,以检查正在执行的方法以及可能的错误
If there is an error after this, then post error from logcat and we will solve it quickly. 如果之后发生错误,请通过logcat发布错误,我们将尽快解决。

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

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