将Json发送到从Web到asp.net的Web服务

时间:2013-11-26 02:38:03

标签: android asp.net json web-services

我想将带有json的http帖子发送到我的webservice。我知道Web服务正在运行,因为我正在使用Postman来测试它。

我的网络服务代码是:

namespace ProyectoFinal.Controllers
 {
[Authorize]
public class HomeController : Controller
{
    private PatientModelDBContext db = new PatientModelDBContext();
    private RootObjectRepository repo = new RootObjectRepository();

    public ActionResult Index()
    {
        ViewBag.Message = "Sistema Medico Integrado";

        return View();
    }

    public ActionResult About()
    {
        ViewBag.Message = "Your app description page.";

        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
    //[HttpPost]
    [AllowAnonymous]
    public ActionResult Insert(string data)
    {
        try
        {
            var recibido = JsonConvert.DeserializeObject<RootObject>(data);
            repo.InsertOrUpdate(recibido);
            repo.Save();
        }
        catch (Exception err)
        {
            return new JsonResult { Data = err.ToString() };
        }
        return new JsonResult { Data = "Eureka" };
    }

    public ActionResult EmergencyRoom()
    {
        return View(db.RootObjects.ToList());
    }

}

}

android中的代码是:

HttpClient client = new DefaultHttpClient();
    try {
        String SendBookingURL= "http://pruebaproyectosmi.azurewebsites.net/home/Insert?data=";
        HttpPost post = new HttpPost(SendBookingURL);       
        HttpResponse response;
        String klk =  URLEncoder.encode(json, "UTF-8");

        StringEntity se = new StringEntity(klk); 
        System.out.println("URL: " + klk);
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "POST/"));
        post.setEntity(se);

        try {
            response = client.execute(post);
            System.out.println("URL: " + response);
            HttpEntity entity = response.getEntity();
            if(entity != null) {
                String ResponseSummaryTable = EntityUtils.toString(entity);
                System.out.println("body" + ResponseSummaryTable);
            }
        }
          catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), (CharSequence) e, 3000).show();
            }
       }
            catch(Exception e){
                e.printStackTrace();
            }      

并且给我的错误是:

I/System.out(17968): body"System.NullReferenceException: Object reference not set to an instance of an object.\r\n   at ProyectoFinal.Models.RootObjectRepository.InsertOrUpdate(RootObject rootobject)\r\n   at ProyectoFinal.Controllers.HomeController.Insert(String data)"

当web服务获取json时,它支持返回“eureka”;

1 个答案:

答案 0 :(得分:3)