繁体   English   中英

如何将发布请求从 Android 发送到 C# Web API

[英]How to send post request from Android to a C# web API

正如我的问题所述,我有 ac# web API (MVC.NET web API 2) 和一个控制器,它有一个 POST 方法,可以接收 post 请求 (Json String) 并简单地将它写入日志文件(为简单起见,确保我已从 android 应用程序收到它)。 另一方面,我有一个 Android 应用程序,它使用 Volley 向提到的 API 发送一个 post 字符串请求。 我使用了几种方法,例如使用 Stringrequest、JsonObject 请求等,但它们似乎都不起作用(我收到 400 错误代码)。 我已经在 postman 中测试了 API,一切正常……我在 API post 方法中收到了发布的字符串。 如果我无法完成此任务,请帮助我,否则我的工作将悬而未决。 提前致谢。 我的代码附在下面:

Web API 控制器

    public class TestController : ApiController
    {
        // POST: api/test
        [HttpPost]
        [Route("api/test")]
        public void Post()
        {
            string param = Request.Content.ReadAsStringAsync().Result;
            EventLogger.writeErrorLog("Posted payload --> " + param)
        }
   }

发送帖子的Android代码

private void postDummy() {
    String url = "http://10.0.2.2:1106/api/test";

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    JSONObject jsonBodyObj = new JSONObject();

    try{
        jsonBodyObj.put("payload", "XYZ");
    }catch (JSONException e){
        e.printStackTrace();
    }
    final String requestBody = jsonBodyObj.toString();
    Log.d("Json :--> ", requestBody);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
            url, null, new Response.Listener<JSONObject>(){
        @Override    public void onResponse(JSONObject response) {
            Log.i("Response",String.valueOf(response));
        }
    }, new Response.ErrorListener() {
        @Override    public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    }){
        @Override
        public String getBodyContentType() {
            return "application/json";
        }

        @Override
        public byte[] getBody() {
            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;
            }
        }
    };

    requestQueue.add(jsonObjectRequest);
}

来自 Android Studio 的错误日志

D/Json :-->: {"payload":"XYZ"}

E/Volley:[561] BasicNetwork.performRequest: http ://10.0.2.2:1106/api/test 的意外响应代码 400: 1 6.onErrorResponse:错误:

Postman 测试结果Web API 测试结果截图

我的情况非常相似,当我从 android volley(带有自定义标头)调用时,C# web API 返回 400。 解决方案(在我的情况下)很简单,只是我删除了“Content-Type”“application/json”并让 volley 做任何事情。

我的代码工作:ANDROID:

                try{
                JSONObject postparams = new JSONObject();
                postparams.put("param1", "1");
                postparams.put("param2", "2");
                String URL=sesion.urlAire + "api/adjunto/getArchivo";
                RequestQueue requestQueue= Volley.newRequestQueue(context);
                JsonObjectRequest objectRequest=new JsonObjectRequest(
                    Request.Method.POST,
                    URL,
                    postparams,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject  response) {
                            //do something
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            //do something
                        }
                    }
                )
                {
                    @Override
                    public Map getHeaders() throws AuthFailureError {
                        HashMap headers = new HashMap();
                        //headers.put("Content-Type", "application/json");
                        headers.put("authorization", sesion.token);
                        return headers;
                    }
                };
                requestQueue.add(objectRequest);

            }catch (Exception e){}

C#:

    [HttpPost]
    public CustomObject getArchivo(PostData postData) {
        return new CustomObject{ param1="1" };
    }

暂无
暂无

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

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