繁体   English   中英

无法将数据从Android发布到WCF

[英]UNABLE to POST data to WCF from Android

我正在尝试从Android应用程序将数据发送到WCF服务,但是似乎无法通过android调用该服务。 我通过LOGCAT中的adnroid收到了STATUSCODE值= 500(这意味着内部服务器错误),我通过源代码执行了100次,但没有发现错误。 并几乎检查了与我的问题有关的所有帖子,但仍然没有任何解决方案。

这是代码

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");
}
}

除了调用WCF服务之外,一切在android代码中都可以正常工作。 我多次调试代码,并收到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上发布。 并且我还使用Google Chrome扩展程序SIMPLE REST CLIENT检查了该服务,并收到内部服务器错误

问题在于您的主机名与您在电话中使用的主机名不匹配。

您可以关闭地址过滤器以临时解决此问题:

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

但是发布到生产环境时,您应该修复主机名

在您的计算机中创建一个具有正确端口号的域,并确保您能够使用Google的Rest客户端调用该服务。如果该域名有效,那么如果您使用android手机调用该服务,则不会发现任何问题。

以下文章将帮助您设置具有正确端口号的虚拟目录。[http://www.hosting.com/support/iis7/create-new-sites-in-iis-7/]

请注意,您不能直接从您的移动电话调用本地主机。至少尝试使用ipaddress调用服务。[http:// localhost / service / mycar] => [http:// DemoService / service / mycar]

以下代码将帮助您稍微深入地调试代码。

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();
}

没关系,我在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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM