如何添加请求正文?

时间:2019-06-19 19:14:52

标签: android android-volley

如何像使用Postman的body选项卡一样将请求正文添加到我的代码中。我只找出请求标头。 

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView textView = findViewById(R.id.textView);
        String url = "url";
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e("Response : ",response.toString());
                textView.setText("Success!");
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Response error : ",error.toString());
                error.printStackTrace();
                textView.setText("Failed!");
            }
        }) 
        {
            @Override
            public Map getHeaders() throws AuthFailureError {
                HashMap headers = new HashMap();
                headers.put("accept-language","EN");
                headers.put("authorization","<autho>");
                headers.put("requestUId","<requestID>");
                headers.put("resourceOwnerId","<resorceOwnerID>");
                return headers;
            }
        };
        requestQueue.add(objectRequest);
    }
}

参考邮递员的头部标签:

https://s3.amazonaws.com/postman-static-getpostman-com/postman-docs/58960775.png

谢谢

1 个答案:

答案 0 :(得分:0)

按如下所示创建您的JSONObject请求:

JSONObject jsonBody = new JSONObject();

try {
    jsonBody.put("firstname", "asd");
    jsonBody.put("lastname", "asd");
    jsonBody.put("id", "1");
} catch (JSONException e) {
    e.printStackTrace();
}

然后JsonObjectRequest()构造函数中的第三个参数是请求,您当前正在传递null。将其替换为jsonBody

修改

如果要在请求正文中发送参数,还必须将HTTP方法更改为POST而不是GET。