从Android应用程序发送到Web服务的WCF反序列化的JSON对象发送到、应用程序、对象、序列化

2023-09-12 06:50:34 作者:伤感在游骋

我想要一个JSON对象发送到我的web服务的方法,该方法是这样定义的:

 公共字符串SendTransaction(串反)
{
            VAR json_serializer =新JavaScriptSerializer();
            交易transObj = json_serializer.Deserialize&其中;交易>(反式);
            返回transObj.FileName;
}
 

在哪里我想回到我得到作为参数此JSON字符串的文件名。

在code的Andr​​oid应用程序:

  HttpPost请求=新HttpPost(
                http://10.118.18.88:8080/Service.svc/SendTransaction);
        request.setHeader(接受,应用/ JSON);
        request.setHeader(内容型,应用/ JSON);

        //构建JSON字符串
        JSONStringer jsonString;

        jsonString =新JSONStringer()
                .object()键(IMEI)。值(2323232323)。键(文件名)
                .value的(Finger.NST)endObject()。

        Log.i(JSON字符串:,jsonString.toString());

        StringEntity实体;

        实体=新StringEntity(jsonString.toString(),UTF-8);

        entity.setContentEncoding(新BasicHeader(HTTP.CONTENT_TYPE,
                应用/ JSON));
        entity.setContentType(应用/ JSON);

        request.setEntity(实体);

        //发送请求WCF服务
        DefaultHttpClient的HttpClient =新DefaultHttpClient();

        HTT presponse响应= httpClient.execute(要求);
        HttpEntity httpEntity = response.getEntity();
        XML字符串= EntityUtils.toString(httpEntity);

        Log.i(回应:XML);
        Log.d(WebInvoke,状态:+ response.getStatusLine());
 

我只得到很长的HTML文件了,还告诉我服务器遇到了错误处理请求。并且状态code是 HTTP / 1.1 400错误的请求

我的交易类在C#中这样定义的:

  [DataContract]
公共类交易
{
    [数据成员(NAME =IMEI)
    公共字符串维明{获得;组; }

    [数据成员(名称为文件名)]
    公共字符串文件名{获得;组; }
}
 
Android调用Web服务

我怎样才能做到这一点的方法不对?

修改,这是我的web.config

 < XML版本=1.0&GT?;
<结构>

  <的appSettings>
    <添加键=ASPNET:UseTaskFriendlySynchronizationContext值=真/>
  < /的appSettings>
  <的System.Web>
    <编译调试=真正的targetFramework =4.5/>
    <的httpRuntime targetFramework =4.5/>
  < /system.web>
  < system.serviceModel>
    <行为>

          < endpointBehaviors>
            <行为NAME =htt​​pBehavior>
                < webHttp />
            < /行为>
        < / endpointBehaviors>

      < serviceBehaviors>
        <行为NAME =>
          <! - 为了避免泄露的元数据信息,部署之前的设置值低于假 - >
          < serviceMetadata httpGetEnabled =真httpsGetEnabled =真/>
          <! - 要接收故障异​​常详细信息以进行调试,设置以下为true值。设置为false部署之前,以避免泄露异常信息 - >
          < serviceDebug includeExceptionDetailInFaults =FALSE/>
        < /行为>
      < / serviceBehaviors>
    < /行为>

    < serviceHostingEnvironment multipleSiteBindingsEnabled =真/>
    <服务>
      <服务名称=Service.Service>
        <端点地址=behaviorConfiguration =htt​​pBehavior绑定=的WebHttpBinding合同=Service.IService/>
      < /服务>
    < /服务>

    < protocolMapping>
        <添加绑定=的WebHttpBinding计划=HTTP/>
    < / protocolMapping>

    &所述;! - &所述; serviceHostingEnvironment aspNetCompatibilityEnabled =真multipleSiteBindingsEnabled =真/&GT  - →;
  < /system.serviceModel>
  < system.webServer>
  &所述;! - &所述;模块runAllManagedModulesForAllRequests =真/&GT  - →;
    <! - 
        为了调试过程中浏览Web应用程序根目录,设置以下为true值。
        设置为false部署之前,以避免泄露Web应用程序文件夹的信息。
       - >
    < directoryBrowse启用=真/>
  < /system.webServer>

< /结构>
 

解决方案

@Tobias,这是不是一个答案。但是,由于这是一个有点长的评论,我在这里张贴。也许这可以帮助诊断问题。 [一个完整的工作code]。的

 公共无效TestWCFService()
{
    //启动服务器
    Task.Factory.StartNew(
        (_)=> {
            乌里baseAddress =新的URI(HTTP://本地主机:8080 /测试);
            WebServiceHost主机=新WebServiceHost(typeof运算(TestService的),baseAddress);
            host.Open();
        },空,TaskCreationOptions.LongRunning).Wait();


    //客户
    。VAR jsonString =新JavaScriptSerializer()序列化(新{xaction = {新维明=121212,文件名=Finger.NST}});
    Web客户端WC =新的Web客户端();
    wc.Headers.Add(内容类型,应用/ JSON);
    VAR的结果= wc.UploadString(HTTP://本地主机:8080 /测试/你好,jsonString);
}

[的ServiceContract]
公共类TestService的
{
    [OperationContract的]
    [WebInvoke(RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped)
    公众用户你好(交易xaction)
    {
        返回新用户(){n = 1,名称=乔,Xaction = xaction};
    }

    公共类用户
    {
        公众诠释编号{获得;组; }
        公共字符串名称{;组; }
        公共事务Xaction {获得;组; }
    }

    公共类交易
    {
        公共字符串维明{获得;组; }
        公共字符串文件名{获得;组; }
    }
}
 

I'm trying to send a JSON object to my webservice method, the method is defined like this:

public String SendTransaction(string trans)
{
            var json_serializer = new JavaScriptSerializer();
            Transaction transObj = json_serializer.Deserialize<Transaction>(trans);
            return transObj.FileName;       
}

Where I want to return the FileName of this JSON string that I got as a parameter.

The code for the android application:

HttpPost request = new HttpPost(
                "http://10.118.18.88:8080/Service.svc/SendTransaction");
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");

        // Build JSON string
        JSONStringer jsonString;

        jsonString = new JSONStringer()
                .object().key("imei").value("2323232323").key("filename")
                .value("Finger.NST").endObject();

        Log.i("JSON STRING: ", jsonString.toString());

        StringEntity entity;

        entity = new StringEntity(jsonString.toString(), "UTF-8");

        entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        entity.setContentType("application/json");

        request.setEntity(entity);

        // Send request to WCF service
        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpResponse response = httpClient.execute(request);
        HttpEntity httpEntity = response.getEntity();
        String xml = EntityUtils.toString(httpEntity);

        Log.i("Response: ", xml);
        Log.d("WebInvoke", "Status : " + response.getStatusLine());

I only get a long html file out, which tells me The server has encountered an error processing the request. And the status code is HTTP/1.1 400 Bad Request

My Transaction class is defined in C# like this:

 [DataContract]
public class Transaction
{
    [DataMember(Name ="imei")]
    public string Imei { get; set; }

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

How can I accomplish this in the right way?

EDIT, this is my web.config

 <?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>

          <endpointBehaviors>
            <behavior name="httpBehavior">
                <webHttp />
            </behavior >
        </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
    <services>
      <service name="Service.Service">
        <endpoint address="" behaviorConfiguration="httpBehavior" binding="webHttpBinding" contract="Service.IService"/>
      </service>
    </services>

    <protocolMapping>
        <add binding="webHttpBinding" scheme="http" />
    </protocolMapping>

    <!--<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />-->
  </system.serviceModel>
  <system.webServer>
  <!-- <modules runAllManagedModulesForAllRequests="true"/>-->
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

解决方案

@Tobias, This is not an answer. But since it was a little bit long for comment, I post it here. Maybe it can help to diagnose your problem. [A full working code].

public void TestWCFService()
{
    //Start Server
    Task.Factory.StartNew(
        (_) =>{
            Uri baseAddress = new Uri("http://localhost:8080/Test");
            WebServiceHost host = new WebServiceHost(typeof(TestService), baseAddress);
            host.Open();
        },null,TaskCreationOptions.LongRunning).Wait();


    //Client
    var jsonString = new JavaScriptSerializer().Serialize(new { xaction = new { Imei = "121212", FileName = "Finger.NST" } });
    WebClient wc = new WebClient();
    wc.Headers.Add("Content-Type", "application/json");
    var result = wc.UploadString("http://localhost:8080/Test/Hello", jsonString);
}

[ServiceContract]
public class TestService
{
    [OperationContract]
    [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    public User Hello(Transaction xaction)
    {
        return new User() { Id = 1, Name = "Joe", Xaction = xaction };
    }

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Transaction Xaction { get; set; }
    }

    public class Transaction
    {
        public string Imei { get; set; }
        public string FileName { get; set; }
    }
}