2013-11-26 145 views
0

我想發送一個json到我的web服務的http帖子。我知道Web服務正在工作,因爲即時通訊使用Postman來測試它。發送一個JSON到一個Web服務從android到asp.net

我的web服務代碼是:

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服務ge時t支持它的json返回「eureka」;

+0

我發現這裏的解決方案: [ 1]:http://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data/4073451#4073451 – guelo

回答

相關問題