2012-10-31 103 views
0

我想一個JSON對象發送到我的web服務方法反序列化JSON對象,方法是這樣定義的:從Android應用程序發送到Web服務WCF

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

,我想回到這個文件名作爲參數獲取的JSON字符串。

爲Android應用程序的代碼:

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

我只得到一個長期的HTML文件時,它告訴我The server has encountered an error processing the request。而狀態代碼HTTP/1.1 400 Bad Request

我的交易類在C#中這樣定義:

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

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

我怎樣才能做到這一點的方法不對?

編輯,這是我的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> 
+0

我的猜測:這是您的服務的配置 –

+0

請你看看我的編輯有關係嗎? –

+0

那麼,我一直很難讀取配置文件。你嘗試裝飾你的方法,如'[OperationContract] [WebInvoke(RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped)] public String SendTransaction(string trans){}' –

回答

2

@Tobias,這不是一個答案。但是由於評論的時間有點長,我在這裏發表。也許它可以幫助診斷你的問題。 [完整的工作代碼]。

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; } 
    } 
} 
+0

你在wcf服務中定義你的'UriTemplate'在哪裏?爲了從瀏覽器訪問它,我認爲web服務中的每個方法都必須定義這個。第二,你使用什麼類型的方法? 'PUT','POST','GET'? –

+1

@TobiasMoeThorstensen UriTemplate是可選的。如果你想使用另一個uri而不是默認的URI(這是methodname),那麼這是必需的。 'UploadString'方法使用'POST'。 'DownloadString'使用'GET'('WebInvoke'屬性將其定義爲POST,GET爲'WebGet') –

+1

我終於進一步了,我實際上得到了來自我的web服務的響應,但是服務返回的Transaction對象是'null'我懷疑這與客戶端有關。 –

相關問題