2014-01-18 143 views
1

我想從Android應用程序發送數據到WCF服務,但不知何故服務似乎不是通過Android調用。我收到STATUSCODE值= 500通過adnroid在LOGCAT(這意味着內部服務器錯誤)我通過源代碼100次,但沒有找出錯誤。幾乎檢查了所有與我的問題有關的帖子,但仍然沒有得到任何解決方案。無法從Android發佈數據到WCF

這裏是THS CODE

的Android代碼:

private class sendPostData extends AsyncTask<String, Void, String> 
{ 
@Override 
protected String doInBackground(String... params) { 
    // TODO Auto-generated method stub 

    HttpPost request = new HttpPost(LOGIN_SERVICE_URL + "/MyCar"); 
    request.setHeader("Accept", "application/json");    
    request.setHeader("Content-type", "application/json"); 
    JSONStringer getCarInfo; 
    try { 
     getCarInfo = new JSONStringer() 
      .object() 
       .key("myCar") 
        .object() 
         .key("Name").value(edt_carName.getText().toString())         
         .key("Make").value(edt_carMake.getText().toString()) 
         .key("Model").value(edt_carModel.getText().toString()) 
        .endObject() 
       .endObject(); 

    StringEntity entity = new StringEntity(getCarInfo.toString()); 

    request.setEntity(entity); 

    // Send request to WCF service 
    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    HttpResponse response = httpClient.execute(request); 
    Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode()); 
    } 
    catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return null; 
} 

@Override 
protected void onPostExecute(String result) { 
    txt_verif.setText("Success"); 
} 
} 

一切工作在Android的代碼,除了罰款調用WCF服務。我調試代碼幾次和接收的StatusCode = 500

這裏是WCF服務

Service.cs

public class Service1 : IService1 
{ 
    public void UpdateMyCar(myCar myCar) { 

     string strConnectionString = ConfigurationManager.ConnectionStrings["Database1"].ConnectionString; 
     SqlConnection conn = new SqlConnection(strConnectionString); 
     conn.Open(); 
     using (SqlCommand cmd = new SqlCommand("Insert into TestingTable (Name,Make,Model) Values (@Name,@Make,@Model)", conn)) { 

      cmd.Parameters.AddWithValue("@Name", myCar.Name); 
      cmd.Parameters.AddWithValue("@Make", myCar.Make); 
      cmd.Parameters.AddWithValue("@Model", myCar.Model); 

      int queryResult = cmd.ExecuteNonQuery(); 
     } conn.Close(); 
    } 

logcat的

WebInvoke  Saving : 500 

IService1.svc

[ServiceContract] 
public interface IService1 
{ 
    [OperationContract] 
    [WebInvoke(
     Method = "POST", 
     UriTemplate = "MyCar", 
     BodyStyle = WebMessageBodyStyle.WrappedRequest, 
     ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json)] 
    void UpdateMyCar(myCar myCar); 
} 

[DataContract] 
public class myCar 
{ 

    [DataMember(Name="Name")] 
    public string Name 
    { 
     get; 
     set; 
    } 

    [DataMember(Name="Model")] 
    public string Model 
    { 
     get; 
     set; 
    } 

    [DataMember(Name="Make")] 
    public string Make 
    { 
     get; 
     set; 
    } 

的Web.Config

<?xml version="1.0"?> 

<configuration> 
<appSettings/> 
<connectionStrings/> 
<system.web> 
    <compilation debug="true" targetFramework="4.0"> 
    </compilation> 

    <authentication mode="Windows"/> 
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web> 
<system.serviceModel> 
    <services> 
     <service name="CarSercive.Service1" behaviorConfiguration="CarSercive.Service1Behavior"> 
      <!-- Service Endpoints --> 
      <endpoint address="" binding="webHttpBinding" contract="CarSercive.IService1"> 
       <identity> 
        <dns value="localhost"/> 
       </identity> 
      </endpoint> 
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
      <behavior name="CarSercive.Service1Behavior"> 
       <serviceMetadata httpGetEnabled="true"/> 

       <serviceDebug includeExceptionDetailInFaults="false"/> 
      </behavior> 
     </serviceBehaviors> 
    </behaviors> 
</system.serviceModel> 

此服務也IIS發佈。我也檢查了該服務與谷歌Chrome擴展簡單的休息客戶端並收到內部服務器錯誤

+0

是什麼簡單的REST客戶端顯示爲響應主體? WCF會告訴你錯誤的細節,我們需要這些信息。 –

+0

感謝您的回覆。我得到這個 http:// localhost:8259/Service1.svc/MyCar'無法在接收器處理,因爲EndpointDispatcher上的AddressFilter不匹配。檢查發件人和收件人的EndpointAddresses是否同意 –

+0

@GregEnnis我在web.config文件中做了一些機會。我將** Binding =「webHttpBinding」更改爲「wsHttpBinding」**,以便** statuscode **更改爲** 415 ** –

回答

0

沒關係,我已經在的web.config文件提出了一些修改,並得到了解決。 <endpointBehaviors>標記在我的案例和其他一些事情中失蹤了。這裏是web.config文件的更新代碼。

[已更新web.config文件]

<?xml version="1.0"?> 
<configuration> 
<appSettings/> 
    <connectionStrings> 
<add name="DB" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Munyb\Documents\Visual Studio 2010\Projects\CarSercive\CarSercive\App_Data\Database1.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/> 
    </connectionStrings> 
<system.web> 
    <compilation debug="true" targetFramework="4.0"> 
    </compilation> 
    <authentication mode="Windows"/> 
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web> 
<system.serviceModel> 
    <services> 
     <service name="CarSercive.Service1" behaviorConfiguration="RESTfulServ"> 
      <!-- Service Endpoints --> 
    <endpoint address="" binding="webHttpBinding" contract="CarSercive.IService1" behaviorConfiguration="web"></endpoint> 
     </service> 
    </services> 
    <behaviors> 
    <endpointBehaviors> 
    <behavior name="web"> 
     <webHttp/> 
    </behavior> 
    </endpointBehaviors> 
     <serviceBehaviors> 
      <behavior name="RESTfulServ"> 
       <serviceMetadata httpGetEnabled="true"/> 
       <serviceDebug includeExceptionDetailInFaults="false"/> 
      </behavior> 
     </serviceBehaviors> 

    </behaviors> 
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"> 
</serviceHostingEnvironment> 
</system.serviceModel> 
    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"> 
    </modules> 
    </system.webServer> 
</configuration> 
0

問題是你的主機名稱不符合你從手機使用。

您可以關閉地址過濾,以暫時解決這個問題:

[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)] 
public class Service1 : IService1 
{ 
    .... 
} 

但是當你發佈到生產

+0

中仍然出現錯誤。它不適用於我 –

+0

這確實解決了您發佈的錯誤。你現在正在得到一個不同的錯誤。它是什麼? –

+0

是啊@Greg恩尼斯即時得到一個不同的錯誤。 由於EndpointDispatcher中的ContractFilter不匹配而無法在接收方處理。這可能是因爲合同不匹配(發件人和收件人之間的操作不匹配)或發件人和收件人之間的綁定/安全性不匹配。檢查發送方和接收方是否有相同的合同和相同的綁定(包括安全要求,例如消息,傳輸,無)。 –

0

創建你的機器有正確的端口號的域名,你應該解決的主機名和確認您可以使用Google的Rest客戶端撥打該服務。如果它有效,那麼如果您使用Android手機撥打相同的電話,則不會發現任何問題。

下面的文章將有助於適當的端口號設置虛擬目錄。[http://www.hosting.com/support/iis7/create-new-sites-in-iis-7/]

注意你不能直接從你的mobile.atleast調用localhost嘗試用ipaddress調用服務。[http:// localhost/service/mycar] => [http:// DemoService/service/mycar]

+0

感謝您的迴應我沒有測試,一個Android手機。我在模擬器上測試該服務,該模擬器可用於其他服務。 –

+0

即時通過[http://10.0.2.2:port/service/mycar] –

+0

調用該服務,您是否在Google的休息客戶端中獲得了正確的響應? – Arjunan

0

以下代碼將幫助您調試代碼的深度。

catch (Exception ex) 
      { 
       WebException webexception = (WebException)ex; 
       var responseresult = webexception.Response as HttpWebResponse; 

       //Code to debug Http Response 
       var responseStream = webexception.Response.GetResponseStream(); 
       string fault_message = string.Empty; 
       int lastNum = 0; 
       do 
       { 
        lastNum = responseStream.ReadByte(); 
        fault_message += (char)lastNum; 
       } while (lastNum != -1); 
       responseStream.Close(); 
} 
+0

謝謝,我會試試看,然後讓你知道 –