将JSON从Android发布到C#WebAPI

时间:2018-02-17 12:06:45

标签: java c# android

我有以下用C#编写的WebAPI:

[RoutePrefix("api/user")]
public class UserController : ApiController
{
    private IActorSystemShell _actorSystem;

    public UserController(IActorSystemShell actorSystem)
    {
        _actorSystem = actorSystem;
    }

    [HttpPost]
    [Route("AddUser")]
    public async Task AddUser(User user)
    {
        var response = await _actorSystem.EntryPoint
            .Ask<SystemMessages.RequestResponse>(UserMessages.DynamicUserRequestNoResponse
                .Instance(_ => { _.Add(user); }), TimeSpan.FromSeconds(10));

        if (response.Result.HttpResponseCode != HttpStatusCode.OK)
            throw new HttpResponseException(Request.CreateErrorResponse(response.Result.HttpResponseCode,
                response.Result.ErrorMessage));
    }
}

从我的Android应用程序中,我试图通过调用此C#WebAPI来添加用户。以下是Android中的相关代码:

@Override
protected Void doInBackground(PostParams... postParam) {

    HttpURLConnection connection = null;

    try{
        connection = (HttpURLConnection) postParam[0].getmUrl().openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(10000);

        //we know it is if of type user
        User userData = (User)postParam[0].getmPostObject();
        String userJsondata = userData.toJsonString();

        //get writing stream
        OutputStreamWriter outWriter = new OutputStreamWriter(connection.getOutputStream());
        outWriter.write(userJsondata);

        //get response
        int httpResponseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();
    }
    catch (SocketTimeoutException ex){
        //log
    }
    catch (Exception ex) {
        //log
    }
    finally {
        connection.disconnect();
    }
    return null;
}

当命中C#中的断点时,User received的值始终为null。为什么会这样?

以下是User.java类:

public class User extends BaseObservable {

public User() {

}

private String _name = "";
@Bindable
public String get_name() {
    return _name;
}
public void set_name(String _name) {
    this._name = _name;
    notifyPropertyChanged(BR._name);
}

private String _surname = "";
@Bindable
public String get_surname() {
    return _surname;
}
public void set_surname(String _surname) {

    this._surname = _surname;
    notifyPropertyChanged(BR._surname);
}

private String _email = "";
@Bindable
public String get_email() {
    return _email;
}
public void set_email(String _email) {

    this._email = _email;
    notifyPropertyChanged(BR._email);
}

public String toJsonString(){
    JSONObject jObject = new JSONObject();
    try{
        jObject.put("Name", get_name());
        jObject.put("Surname", get_surname());
        jObject.put("Email", get_email());
    } catch (Exception ex){
        Log.d("Error", "User.toJson");
    }
    return jObject.toString();
}

}

这是User.cs类。

public class User : ModelBase
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
}

更新

flush()添加到OutputStreamWriter之后,我现在不再在C#服务器端获取空对象,而是一个对象的属性为空。

我已将代码更新如下:

//get writing stream
        OutputStreamWriter outWriter = new OutputStreamWriter(connection.getOutputStream());
        outWriter.write(userJsondata);
        outWriter.flush();

仅供参考,当我调试并检查userJsonData的值时,我可以看到我的属性已正确设置为输入字段给出的内容

2 个答案:

答案 0 :(得分:0)

当发布的对象太大时我遇到了类似的问题。就我而言,我使用IIS Express进行本地开发。在我们使用IIS的测试环境中,我无法重现它。

您是否尝试使用Fiddler或任何其他工具来模仿相同的请求?

答案 1 :(得分:0)

我得到了成功将数据发布到我的C#WebAPI。这是我更新的代码:

protected Void doInBackground(PostParams... postParam) {

    HttpURLConnection connection = null;

    try{
        connection = (HttpURLConnection) postParam[0].getmUrl().openConnection();
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(10000);

        //we know it is if of type user
        User userData = (User)postParam[0].getmPostObject();
        String userJsondata = userData.toJsonString();

        //get writing stream
        OutputStreamWriter outWriter = new OutputStreamWriter(connection.getOutputStream());
        outWriter.write(userJsondata);
        outWriter.flush();

        //get response
        int httpResponseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();
    }
    catch (SocketTimeoutException ex){
        //log
    }
    catch (Exception ex) {
        //log
    }
    finally {
        connection.disconnect();
    }
    return null;
}

我改变的是,我在请求的标题中添加了内容类型,如下所示:

connection.setRequestProperty("Content-Type", "application/json");

我将数据写入OuputStream后刷新了OutputStreamWriter,如下所示:

outWriter.flush();