c# - 如何将 post 请求从 Android 发送到 C# web API

标签 c# android android-studio asp.net-web-api android-volley

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

Web API Controller

    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| E/截击:1 6.onErrorResponse:错误:

Postman 测试结果 A screenshot for Web API test result

最佳答案

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

我的代码工作: 安卓:

                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" };
    }

关于c# - 如何将 post 请求从 Android 发送到 C# web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54409756/

相关文章:

javascript - 从 EXTJS ComboBox 的 JSON 存储中检索 url 参数

c# - 使用 Linq 选择组中的最大值

c# - Gremlin.Net 在一次遍历中获取边 Id、InV、OutV 和属性

android - 离线时无法与本地主机建立连接

java - Android - 膨胀类 EditText 时出错

c# - 为什么多维数组的枚举值不等于自身?

android - 移动设备是否将其从打瞌睡中唤醒

android - 有没有办法在单击按钮时删除 firebase 数据库父节点?

android - 为什么在 Android Studio 中编程时我的光标会随机消失?

java - splitapkbundle 无效。包目标未知语言 : [gr]