웹 API 설정이 있고 API의 끝점 중 하나가 JSON 개체 (API에서 .NET 개체로 확인 됨)를 사용합니다.
Postman을 사용하여 포스트 엔드 포인트를 성공적으로 호출 할 수 있습니다. 여기 URL이 있습니다.
https://example.com/api/helprequests
그리고 여기 Postman 요청에 포함 된 JSON이 있습니다.
{"Title":"Test Title", "Message":"Test Message"}
Postman에서는 모든 것이 잘 작동하지만 Volley를 사용하여 Android 앱에서이 API를 호출하려고합니다.
다음은 관련 코드입니다.
String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, webAddress,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("RESPONSE", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
@Override
public String getBodyContentType() {
return "application/json";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("Title","Test title");
params.put("Message", "Test message");
} catch (Exception ex) {
VolleyLog.wtf("Unsupported Encoding");
return null;
}
return null;
}
};
queue.add(stringRequest);
이것을 실행하면 다음 오류가 발생합니다.
E/Volley: [50225] BasicNetwork.performRequest: Unexpected response code 500 for https://example.com/api/helprequests
Volley 요청에 게시물 데이터를 어떻게 추가합니까?
대신 사용 StringRequest
할 일 사용을 JsonObjectRequest
.
String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject object = new JSONObject();
try {
object.put("Title", "my title");
object.put("Message", "my message");
} catch (JSONException e) {
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, webAddress,object, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject object) {
Log.d("RESPONSE", object.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("RESPONSE", "That didn't work!");
}
});
queue.add(request);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다