【问题标题】:Using volley to make web service call使用 volley 进行 web 服务调用
【发布时间】:2017-02-07 02:18:16
【问题描述】:

我有一个 web api 设置,API 中的一个端点采用 JSON 对象(在 API 中被解析为 .NET 对象)。

使用 Postman 我可以成功调用 post 端点,这里是 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 请求?

【问题讨论】:

  • 标题和消息是否应该在正文中而不是在标题中?此外,您在正文中返回 null。
  • 我认为title和message应该在body里面——getBody的目的是什么?我从网上的多个地方把它放在一起
  • 不要使用getBody。你有 JSON。 Volley 有 JSON 类。 afzaln.com/volley/com/android/volley/toolbox/…
  • 无论如何,你有一个 500 错误,那么你的服务器说什么是错误的?
  • @andrewb 我可以看看你如何在邮递员中提出请求的截图吗?为了安全起见,只需隐藏您的网址即可。

标签: android json android-volley


【解决方案1】:

不要使用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);

【讨论】:

    【解决方案2】:
    String webAddress = "http://example.com/api/helprequests/";
     RequestQueue queue = Volley.newRequestQueue(this);
    
     JSONObject jsonObject= new JSONObject();
     try {
         jsonObject.put("Title", "my title");
         jsonObject.put("Message", "my message");
     } catch (JSONException e) {
     }
    
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
            JsonObjectRequestWithHeader jsonObjReq = new JsonObjectRequestWithHeader(Request.Method.POST,
                    webAddress , jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.v("Response0", response.toString());
    }
    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d("Response", "Error: " + error.getMessage());
                    pd.dismiss();
    
                }
            });
            int socketTimeout = 50000;//30 seconds - change to what you want
            RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            jsonObjReq.setRetryPolicy(policy);
            queue.add(jsonObjReq);
            return null;
        }
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    猜你喜欢
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2015-04-28
    • 2014-01-24
    • 2012-05-30
    • 1970-01-01
    相关资源
    最近更新 更多