正如我的问题所述,我有一个带有POST方法的控制器的ac#Web API(MVC.NET Web API 2),该控制器接收发布请求(Json字符串)并将其简单地写入日志文件(为简单起见)确保我已从android应用程序收到它)。另一方面,我有一个Android应用程序,该应用程序使用Volley将发布字符串请求发送到提到的API。我已经使用了几种方法,例如使用Stringrequest,JsonObject请求等,但是似乎都不起作用(我得到400错误代码)。我已经在邮递员中测试过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 E / Volley:1 6.onErrorResponse:错误:
答案 0 :(得分:1)
我的情况非常相似,当我从android凌空调用时(带有自定义标头),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" };
}