如何将数据从android传输到服务器

时间:2014-08-20 07:23:16

标签: c# web-services wcf

我创建了android程序,它以JSON格式发送数据,如下所示:

public static String POST(String url, ArrayList<Pers_Ordre>  ListOrdres){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();

        for(Pers_Ordre TheOrdre : ListOrdres){
             jsonObject.accumulate("CodeClient", TheOrdre.getLe_CodeClient());
             jsonObject.accumulate("CodeDest", TheOrdre.getLe_CodeDest());
             jsonObject.accumulate("NoOrdre", TheOrdre.getLe_NoOrdre());
             jsonObject.accumulate("LeDate", "qsdf");
             jsonObject.accumulate("LeGPS", "qsdfqsdf");            
             jsonObject.accumulate("LeStatut", TheOrdre.getLe_Statut());
             jsonObject.accumulate("LeCamion", TheOrdre.getLe_Camion());
            }

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();  

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();  


        // 10. convert inputstream to string 
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else 
            result = "Did not work!"; 

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    } 

    // 11. return result
    return result; 
}

当我调试它时,我的json数据是:

{"LeDate":"20\/08\/2014 09:15","LeStatut":"1","CodeClient":"140056","NoOrdre":"26754","CodeDest":"1026","LeCamion":"Camion A"}

我不知道我是如何在我的WCF程序中使用这个JSON的。我知道它称之为连接并调用我的服务,因为当我用这样的非感知数据进行测试时:

  comm_Insrt.Parameters.AddWithValue("@CODE_CLIENT", "454548");
                    comm_Insrt.Parameters.AddWithValue("@CODE_DEST", "44444");
                    comm_Insrt.Parameters.AddWithValue("@NO_ORDRE", "545454545");
                    comm_Insrt.Parameters.AddWithValue("@DATE_TAMPON", "2013-05-03 15:01:16.920");
                    comm_Insrt.Parameters.AddWithValue("@GPS_POS", "fsdgsgsg");
                    comm_Insrt.Parameters.AddWithValue("@STATUS_ORDRE", "65");
                    comm_Insrt.Parameters.AddWithValue("@CAMION", "fgfgf");
                    comm_Insrt.ExecuteNonQuery(); 

它插入我的SQL sever 2008 R2。

这是我的服务:

namespace WcfService_SuiviColis
{
    // REMARQUE : vous pouvez utiliser la commande Renommer du menu Refactoriser pour changer le nom de classe "Service1" dans le code, le fichier svc et le fichier de configuration.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class Service1 : IService1
    {
       // public void SaveData(string CodeClient, string CodeDest, string NoOrdre, string LeDate, string LeGPS, string LeStatut, string LeCamion)
        public void SaveData(Pers_Ordre_NET Oodre)
        { 
            try
            {
                //var data = Oodre.Split('|');
                //var response = new Pers_Ordre_NET
                //{
                //    CodeClient = data[0],
                //    CodeDest = data[1],
                //    NoOrdre = data[2],
                //    LeDate = data[3]
                //};      

                using (var connectionWrapper = new Connexion())
                {
                    var connectedConnection = connectionWrapper.GetConnected();
                    string sql_Adding = "INSERT INTO [SUIVI_ORDRE]"+
                                          " ([CODE_CLIENT] ,[CODE_DEST],[NO_ORDRE],[DATE_TAMPON],[GPS_POS],[STATUS_ORDRE],CAMION)"+
                                    "VALUES (@CODE_CLIENT,@CODE_DEST,@NO_ORDRE,@DATE_TAMPON,@GPS_POS,@STATUS_ORDRE,@CAMION)";
                    SqlCommand comm_Insrt = new SqlCommand(sql_Adding, connectionWrapper.conn);
                    comm_Insrt.Parameters.AddWithValue("@CODE_CLIENT", Oodre.CodeClient);
                    comm_Insrt.Parameters.AddWithValue("@CODE_DEST", Oodre.CodeDest);
                    comm_Insrt.Parameters.AddWithValue("@NO_ORDRE", Oodre.NoOrdre);
                    comm_Insrt.Parameters.AddWithValue("@DATE_TAMPON", Oodre.LeDate);
                    comm_Insrt.Parameters.AddWithValue("@GPS_POS", Oodre.LeGPS);
                    comm_Insrt.Parameters.AddWithValue("@STATUS_ORDRE", Oodre.LeStatut);
                    comm_Insrt.Parameters.AddWithValue("@CAMION", Oodre.LeCamion);

                    //comm_Insrt.Parameters.AddWithValue("@CODE_CLIENT", "454548");
                    //comm_Insrt.Parameters.AddWithValue("@CODE_DEST", "44444");
                    //comm_Insrt.Parameters.AddWithValue("@NO_ORDRE", "545454545");
                    //comm_Insrt.Parameters.AddWithValue("@DATE_TAMPON", "2013-05-03 15:01:16.920");
                    //comm_Insrt.Parameters.AddWithValue("@GPS_POS", "fsdgsgsg");
                    //comm_Insrt.Parameters.AddWithValue("@STATUS_ORDRE", "65");
                    //comm_Insrt.Parameters.AddWithValue("@CAMION", "fgfgf");
                    comm_Insrt.ExecuteNonQuery();                   
                }
            }
            catch (Exception excThrown)
            {
                throw new Exception(excThrown.Message);
            }
        }    
    }   
}

和我的Iservice:

namespace WcfService_SuiviColis
{
    // REMARQUE : vous pouvez utiliser la commande Renommer du menu Refactoriser pour changer le nom d'interface "IService1" à la fois dans le code et le fichier de configuration.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
        //void SaveData(string CodeClient, string CodeDest, string NoOrdre, string LeDate, string LeGPS, string LeStatut, string LeCamion);      
        void SaveData(Pers_Ordre_NET Oodre);      
    }

    [DataContract]
    public class Pers_Ordre_NET
    {
        [DataMember]
        string _CodeClient;
        public string CodeClient
        {
            get { return _CodeClient; }
            set { _CodeClient = value; }
        }

       [DataMember]
        string _CodeDest;
        public string CodeDest
        {
            get { return _CodeDest; }
            set { _CodeDest = value; }
        }

        [DataMember]
        string _NoOrdre;
        public string NoOrdre
        {
            get { return _NoOrdre; }
            set { _NoOrdre = value; }
        }

        [DataMember]
        string _LeDate;
        public string LeDate
        {
            get { return _LeDate; }
            set { _LeDate = value; }
        }

        [DataMember]
        string _LeGPS;
        public string LeGPS
        {
            get { return _LeGPS; }
            set { _LeGPS = value; }
        }

        [DataMember]
        string _LeStatut;
        public string LeStatut
        {
            get { return _LeStatut; }
            set { _LeStatut = value; }
        }

        [DataMember]
        string _LeCamion;
        public string LeCamion
        {
            get { return _LeCamion; }
            set { _LeCamion = value; }
        }
    }

}

和web.cofig:

 <system.serviceModel>  

    <services>
        <service name="WcfService_SuiviColis.Service1" behaviorConfiguration="ServiceBehaviour">
            <!--<endpoint address="web" binding="webHttpBinding" contract="WcfService_SuiviColis.IService1" behaviorConfiguration="httpBehavior" />
              <endpoint address="" binding="basicHttpBinding"   contract="WcfService_SuiviColis.IService1"  />-->

            <endpoint address="FA" binding="webHttpBinding" contract="WcfService_SuiviColis.IService1" behaviorConfiguration="web" bindingConfiguration="defaultRestJsonp" />

        </service>
   </services>  

    <behaviors> 
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">       
          <serviceMetadata httpGetEnabled="true" />          
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
        <endpointBehaviors>
            <behavior name="web">
                <dataContractSerializer maxItemsInObjectGraph="2147483647" />
                <webHttp />
            </behavior>
        </endpointBehaviors>
    </behaviors>

      <bindings>
          <webHttpBinding>
              <binding name="defaultRestJsonp" crossDomainScriptAccessEnabled="true">
                  <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="64" maxNameTableCharCount="2147483647" />
                  <security mode="None" />
              </binding>
          </webHttpBinding>
      </bindings>  

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true">


      </serviceHostingEnvironment>




  </system.serviceModel>
 <system.webServer>


     <directoryBrowse enabled="true" />
    <modules runAllManagedModulesForAllRequests="true" />
        <handlers>
            <add name="JSON" path="*.json" verb="*" type="c:\WINDOWS\System32\inetsrv\asp.dll" resourceType="Unspecified" preCondition="integratedMode" />
        </handlers>
  </system.webServer>

EDITED

我也尝试以字符串格式获取数据,然后我会像这样使用它:

   public void SaveData(String Oodre)
            { 
                try
                {
                    var data = Oodre.Split(',');
                    var response = new Pers_Ordre_NET
                    {
                        CodeClient = data[0],
                       CodeDest = data[1],
                        NoOrdre = data[2],
                       LeDate = data[3]
                   }; 

但是我遇到了错误问题,对象类型为String的deserialiosation,找到了元素LeDate ....

我也试过这样:

  public void SaveData(byte[] abc)
        { 
            try
            {  

                Stream strm = new MemoryStream(abc);
                DataContractSerializer obj = new DataContractSerializer(typeof(string));
                string result = obj.ReadObject(strm).ToString();

仍然是同样的错误....我如何在WCF中使用JSON数据?

1 个答案:

答案 0 :(得分:0)

我解决了。只需将名称放在数据成员

 [DataContract]
    public class Pers_Ordre_NET
    {
        [DataMember(Name = "CodeClient")]
        string _CodeClient;
        public string CodeClient
        {
            get { return _CodeClient; }
            set { _CodeClient = value; }
        }

       [DataMember(Name = "CodeDest")]
        string _CodeDest;
        public string CodeDest
        {
            get { return _CodeDest; }
            set { _CodeDest = value; }
        }

        [DataMember(Name = "NoOrdre")]
        string _NoOrdre;
        public string NoOrdre
        {
            get { return _NoOrdre; }
            set { _NoOrdre = value; }
        }

        [DataMember(Name = "LeDate")]
        string _LeDate;
        public string LeDate
        {
            get { return _LeDate; }
            set { _LeDate = value; }
        }

        [DataMember(Name = "LeGPS")]
        string _LeGPS;
        public string LeGPS
        {
            get { return _LeGPS; }
            set { _LeGPS = value; }
        }

        [DataMember(Name = "LeStatut")]
        string _LeStatut;
        public string LeStatut
        {
            get { return _LeStatut; }
            set { _LeStatut = value; }
        }

        [DataMember(Name = "LeCamion")]
        string _LeCamion;
        public string LeCamion
        {
            get { return _LeCamion; }
            set { _LeCamion = value; }
        }