簡體   English   中英

無法使用Android客戶端發布到WCF服務

[英]Unable to POST to WCF service using Android client

我有一個自托管的WCF Web服務正在運行,還有一個Android客戶端應用程序。 我能夠以json格式從Web服務獲取或檢索數據,但是我無法發布信息或將任何數據發送到服務器。

下面是來自WCF服務的代碼:

 [OperationContract]
 [WebInvoke(Method = "POST",
 UriTemplate = "/SetValue",
 RequestFormat = WebMessageFormat.Json,
 ResponseFormat = WebMessageFormat.Json,
 BodyStyle = WebMessageBodyStyle.Wrapped)]
 public string SetValue(TestClass someValue)
 {
     return someValue.Something.ToString();
 }

[DataContract]
public class TestClass
{
    [DataMember(Name = "something")]
    public int Something
    {
        get;
        set;
    }
}

以下是來自Android客戶端的代碼:

 HttpClient httpClient = new DefaultHttpClient();
 HttpPost request = new HttpPost("http://xxx.xxx.x.x:8000/SetValue");
 List<NameValuePair> params = new ArrayList<NameValuePair>(1);
 params.add(new BasicNameValuePair("something", "12345"));
 request.setEntity(new UrlEncodedFormEntity(params));
 HttpResponse response = httpClient.execute(request);

以下是我如何啟動自托管服務:

 class Program
 {
    static void Main()
    {
        Uri baseAddress = new Uri("http://localhost:8000/");

        using (WebServiceHost host = new WebServiceHost(typeof(ServerSideProfileService), baseAddress))
        {
            host.AddServiceEndpoint(typeof(ServerSideProfileService), new BasicHttpBinding(), "Soap");
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ServerSideProfileService), new WebHttpBinding(), "Web");
            endpoint.Behaviors.Add(new WebHttpBehavior());

            // Open the service host, service is now listening
            host.Open();
        }
     }
  }

我只有一個app.config,它只有:

 <?xml version="1.0"?>
 <configuration>
 <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

當我從Android客戶端運行httpClient.execute(request)時得到的響應包括:

 HTTP/1.1 400 Bad Request
 Request Error
 The server encountered an error processing the request. See server logs for more details.

就是這樣。 我是WCF的新手,不知道此“服務器日志”在哪里,並且對如何進行故障排除或調試感到迷惑? (我嘗試過Fiddler2,但似乎無法從Android客戶端檢測到任何東西。)

[編輯]

我也嘗試過

 JSONObject json = new JSONObject(); 
 json.put("something", "12345"); 
 StringEntity entity = new StringEntity(json.toString()); 
 entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
 entity.setContentType( new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));  
 request.setEntity(entity); 

這也會導致錯誤。

我還注意到,如果我更改“ SetValue”以返回常量,例如“ abcd”,而不是someValue.Something.ToString(),那么一切正常嗎?

您的客戶端代碼正在發送html表單發布格式的有效負載,但是您的服務器需要json有效負載,因此您需要使客戶端類似於

HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://xxx.xxx.x.x:8000/SetValue");
StringEntity e = new StringEntity("{ \"something\":12345 }", "UTF-8");
request.setEntity(e);
request.setHeader("content-type", "application/json");
HttpResponse response = httpClient.execute(request);

我有同樣的問題,我通過刪除解決了

BodyStyle = WebMessageBodyStyle.WrappedRequest

從我的WCF方法標頭

 [WebInvoke(Method = "POST", UriTemplate = "mymethod", RequestFormat=WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
                ResponseFormat=WebMessageFormat.Json)]

變成

 [WebInvoke(Method = "POST", UriTemplate = "mymethod", RequestFormat=WebMessageFormat.Json,
                ResponseFormat=WebMessageFormat.Json)]
    [WebInvoke(UriTemplate = "crud/delete",
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        Method = "POST"
    )]        
    public SampleItem Delete(string id)
    {
        SampleItem item = new SampleItem();
        item.Id = 118;
        item.StringValue = id;
        return item;
        throw new NotImplementedException();
    }


var params  = '{"id":"sfs"}';

function postTest0(){
    $.ajax({
        url:'http://localhost/wcfrest/rest/crud/delete',
        //url:'http://localhost/wcfrest/rest/crud/create', //后台處理程序
        type:'post',    //數據發送方式
        dataType:'json', //接受數據格式
        contentType: "application/json",
        data:params, //要傳遞的數據
        timeout:1000,
        error:function(){alert('post error');},
        success:update_page //回傳函數(這里是函數名)
    });
}

superfell那個正解!

根據我發現的內容,Android將JSON字符串轉換為字節數組流,然后將其發布。 這是我自己的代碼作為示例

HttpPost httpPost = new HttpPost(URL_Base + uri);
httpPost.setEntity(new StringEntity(sJSONOut));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpEntity oHttpEntity = new DefaultHttpClient().execute(httpPost).getEntity();

在eclipse中,當在倒數第二行上設置斷點並檢查httpPost對象屬性時,我發現我的StringEntity的值不是字節數組[123。 43,234 ......即使我已經確認我的字符串sJSONOut的格式正確為json。

這里的另一個答案建議從WCF方法標頭中刪除BodyStyle = WebMessageBodyStyle.WrappedRequest。 這為我提供了將那條線從WrappedRequest更改為Bare所需的線索,這最終起作用了。

BodyStyle = WebMessageBodyStyle.Bare

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM