首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从Android向C# web发送post请求

如何从Android向C# web发送post请求
EN

Stack Overflow用户
提问于 2019-01-28 20:25:20
回答 1查看 2.3K关注 0票数 1

正如我的问题所述,我有一个c# web (MVC.NET web 2),其控制器具有POST方法,该方法接收post请求(Json )并简单地将其写入日志文件(为了简单起见,只需确保从android接收到它)。另一方面,我有一个Android应用程序,它使用Volley向所提到的API发送post字符串请求。我使用了几种方法,例如使用Stringrequest、JsonObject请求等,但似乎没有一种方法有效(我得到了400个错误代码)。我已经在postman中测试了API,一切都很好.我在API方法中接收发布的字符串。如果我没能完成这一任务,请帮助我,否则我的工作将处于平衡状态。提前谢谢。我的代码随函附上:

网络API控制器

代码语言:javascript
运行
复制
    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代码发送

代码语言:javascript
运行
复制
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 的错误日志

代码语言:javascript
运行
复制
D/Json :-->: {"payload":"XYZ"}

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

邮差测试结果 Web测试结果的截图

EN

回答 1

Stack Overflow用户

发布于 2019-08-01 21:35:51

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

我的代码工作: ANDROID:

代码语言:javascript
运行
复制
                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#:

代码语言:javascript
运行
复制
    [HttpPost]
    public CustomObject getArchivo(PostData postData) {
        return new CustomObject{ param1="1" };
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54409756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档