Android发送数据到web端,Xamarin Android将Post数据发送到WebApi

I have an Android app created with Xamarin in Visual Studio and I want to send a form data in json format to a Web Api created in C#. I tried a lot of methods from web an none worked.

Sometimes I get 500 Internal Server Error or sometimes I get null.

The last version I tried in WebApi is:

public HttpResponseMessage Post([FromBody]string value)

{

if (value == null || value == "") Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read subject/tutor from body");

var user = JsonConvert.DeserializeObject(value);

dynamic json = System.Web.Helpers.Json.Decode(value);

string newName = json.Name;

string newSurname = json.Surname;

string newUsername = json.Username;

string newPassword = json.Password;

string insertNewUser = "INSERT INTO USERS(NAME,SURNAME,USERNAME,PASSWORD) VALUES (:name,:surname,:username,:password) ";

using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["Licenta"].ConnectionString))

{

OracleCommand cmd = new OracleCommand(insertNewUser, conn);

cmd.Parameters.Add("name", newName);

cmd.Parameters.Add("surname", newSurname);

cmd.Parameters.Add("username", newUsername);

cmd.Parameters.Add("password", newPassword);

cmd.ExecuteNonQuery();

}

return Request.CreateResponse(HttpStatusCode.OK);

}

catch(Exception ex)

{

return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);

}

}

The message I want to send to Web api is

{

"name": "Ionescu",

"surname": "Ralu",

"username": "ralucuta",

"password": "1235555",

"usertype":1

}

This is my Xamarin Android app code:

public async Task SaveProduct(UserAccount product)

{

using (var client = new HttpClient())

{

client.BaseAddress = new Uri("http://blabla:80/test/");

client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

StringContent content = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json");

// HTTP POST

HttpResponseMessage response = await client.PostAsync("api/Users/", content);

if (response.IsSuccessStatusCode)

{

string data = await response.Content.ReadAsStringAsync();

product = JsonConvert.DeserializeObject(data);

}

}

return product;

}

public class UserAccount

{

public string name { get; set; }

public string surname { get; set; }

public string username { get; set; }

public string password { get; set; }

public int usertype { get; set; }

}

Talk1:

Did you test the Web Api with some REST testing tool like POSTMAN, to verify that it works with your JSON data?

Talk2:

I tested with Restlet Client extension from Chrome and did not worked with anything. I thought I do not receive and read data correctly

Talk3:

Can you try creating a controller method like this one: stackoverflow.com/a/21579294/915414 - just use UserAccount instead of PersonModel, and test it with Restlet Client

Talk4:

I think this is webAPI's issue, did you route it correctly? You should make it works on the testing tool like PostMan and then test with Mobile.

Talk5:

it's webAPI's issue please check your webAPI. and test with Postman

Solutions1

Your rest api won't be called since you are passing UserAccount object and you are expecting string. change your web api signature like this

[HttpPost]

[Route("api/Users/save")]

public HttpResponseMessage MyMethod(UserAccount userAccount)

{

//your api code

}

And in your android code

public async Task SaveProduct(UserAccount product)

{

try {

using (var client = new HttpClient ()) {

client.BaseAddress = new Uri ("http://blabla:80/test/");

client.DefaultRequestHeaders.Accept.Clear ();

client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/json"));

var uri = new Uri ("http://blabla:80/test/api/Users/save");

string serializedObject = JsonConvert.SerializeObject (product);

HttpContent contentPost = new StringContent (serializedObject, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync (uri, contentPost);

if (response.IsSuccessStatusCode) {

var data = await response.Content.ReadAsStringAsync ();

UserAccount product = JsonConvert.DeserializeObject(data);

return product;

}

}

}

catch (Exception) {

return null;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值