Android、Xamarin、Rest - 如何在请求中传递对象

Android, Xamarin, Rest - how to pass object in the request

我有一个简单的服务器休息端点正在运行 Spring -

@RestController
@RequestMapping("/services")
@Transactional
public class CustomerSignInService {

    @Autowired
    private CustomerDAO customerDao;

    @RequestMapping("/customer/signin")
    public Customer customerSignIn(@RequestParam(value = "customer") Customer customer) {
        //Some Code Here...
        return customer;
    }
}

我正在尝试使用此方法从我的 Xamarin Android 应用传递客户对象 -

public JsonValue send(String url, SmartJsonSerializer obj)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
    request.ContentType = "application/json";
    request.Method = "POST";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(obj.toJsonString());
    }

    using (WebResponse response = request.GetResponse())
    {
        using (Stream stream = response.GetResponseStream())
        {
            return JsonObject.Load(stream);
        }
    }
}

但我不断收到错误请求异常(Http 错误 400),显然我在服务器端的代码没有被触发。

SmartJsonSerializer 使用 JSON.NET 将 Customer 对象序列化为字符串 -

using System;
using Newtonsoft.Json;

namespace Shared
{
    public class SmartJsonSerializer
    {        
        public string toJson()
        {
            return JsonConvert.SerializeObject(this);
        }
    }
}

感谢任何帮助, 谢谢!

通常,如果您要像这样将复杂对象发布到 api,您会将其写入请求正文。您似乎确实在 android 方面这样做。

我不熟悉 Spring,但看起来您希望 customer 作为 url 参数 - 尝试将 @RequestParam 替换为 @RequestBody .

我纠结了一段时间,但显然可以在服务器端找到解决方案。

如果有帮助,可以看看这个

@RestController
@RequestMapping("/services")
@Transactional
public class SomeService {

                @RequestMapping(value = "/user/signin", method = RequestMethod.POST)
                @ResponseBody
                public AppUser signIn(@RequestBody AppUser appUser) {
                                appUser.invoke();
                                return appUser;
                }
}