无法使用Android客户端POST到WCF服务

时间:2011-05-17 19:30:35

标签: android wcf json service client

我有一个运行的自托管WCF Web服务和一个Android客户端应用程序。我能够以json格式从Web服务获取或检索数据,但是我无法POST或向服务器发送任何数据。

以下是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(),那么一切正常吗?

4 个答案:

答案 0 :(得分:2)

您的客户端代码正在发送格式化有效负载的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);

答案 1 :(得分:2)

我有同样的问题,我通过删除

解决了这个问题
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)]

答案 2 :(得分:0)

    [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 //回传函数(这里是函数名)
    });
}

超级那个正解!

答案 3 :(得分:0)

根据我的发现,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

相关问题