簡體   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