我希望按照图片说:
以下是我试图从该图片中实现的代码:
RequestQueue queue = Volley.newRequestQueue(this); String url =" https://api.kairos.com/enroll" ;;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.i("Response is: " , response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// mTextView.setText("That didn't work!");
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("app_id", "4985f625");
params.put("app_key", "aa9e5d2ec3b00306b2d9588c3a25d68e");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
现在我不知道如何将JSONObject部分添加到我的POST请求中,以及如何添加Content-Type标头。请帮我解决这个问题。
答案 0 :(得分:0)
我发现了一个类似的问题here。请参阅下面的代码。您必须覆盖getBodyContentType
方法。
public String getBodyContentType()
{
return "application/json";
}
答案 1 :(得分:0)
对于内容类型标题,您可以执行以下操作
StringRequest request = new StringRequest(Request.Method.PUT,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
listener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(@NonNull VolleyError error) {
if (error.networkResponse != null) {
errorListener.onErrorResponse(error.networkResponse.statusCode, null);
} else {
Log.e(TAG, "An error occurred while trying to verify sms: ", error);
errorListener.onErrorResponse(500, null);
}
}
}) {
@NonNull
@Override
protected Map<String, String> getParams() {
return data;
}
@NonNull
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type",
"application/x-www-form-urlencoded");
return headers;
}
};
对于发送Json对象,我建议像这样创建Json对象
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("11", 3);
jsonObject.put("12", 4);
jsonObject.put("13", 5);
} catch (JSONException e) {
e.printStackTrace();
}
然后你可以通过jsonObject.toString()
将这个对象作为字符串传递,并将其传递给参数,例如传递任何字符串,如下所示
@NonNull
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("json", jsonObject.toString();
return params;
}