繁体   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