[英]Unable to POST to WCF service using Android client
I have a self-hosted WCF web service running, and an Android client application. 我有一个自托管的WCF Web服务正在运行,还有一个Android客户端应用程序。 I am able to GET or retrieve data from the web service in json format, however I am unable to POST or send any data to the server.
我能够以json格式从Web服务获取或检索数据,但是我无法发布信息或将任何数据发送到服务器。
Below is the code from the WCF service: 下面是来自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;
}
}
Below is the code from the Android client: 以下是来自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);
The following is how I start the self-hosted service: 以下是我如何启动自托管服务:
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();
}
}
}
I only have an app.config which just has: 我只有一个app.config,它只有:
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
The response I'm getting when I run httpClient.execute(request) from the Android client includes: 当我从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.
And that's pretty much it. 就是这样。 I am very new to WCF and don't know where this 'server log' would be, and am at a loss as to how to troubleshoot or debug this?
我是WCF的新手,不知道此“服务器日志”在哪里,并且对如何进行故障排除或调试感到迷惑? (I have tried Fiddler2 but it doesn't seem to detect anything from the Android client.)
(我尝试过Fiddler2,但似乎无法从Android客户端检测到任何东西。)
[EDIT] [编辑]
I have also tried 我也尝试过
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);
which also results in the error. 这也会导致错误。
I also noticed that if I change 'SetValue' to return a constant, such as "abcd", instead of someValue.Something.ToString(), then everything works? 我还注意到,如果我更改“ SetValue”以返回常量,例如“ abcd”,而不是someValue.Something.ToString(),那么一切正常吗?
Your client code is sending a html form post formatted payload, but your server is expecting a json payload, you need the client to be something like 您的客户端代码正在发送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);
I had the same problem, I resolved this by removing 我有同样的问题,我通过删除解决了
BodyStyle = WebMessageBodyStyle.WrappedRequest
from my WCF method header 从我的WCF方法标头
[WebInvoke(Method = "POST", UriTemplate = "mymethod", RequestFormat=WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat=WebMessageFormat.Json)]
Changed to 变成
[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 那个正解! superfell那个正解!
From what I have found Android converts the JSON string to a byte array stream and then posts it. 根据我发现的内容,Android将JSON字符串转换为字节数组流,然后将其发布。 Here is my own code as an example
这是我自己的代码作为示例
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();
In eclipse, when setting a break point on the second to last line and inspecting the httpPost object properties i find the value of my StringEntity is not a byte array [123. 在eclipse中,当在倒数第二行上设置断点并检查httpPost对象属性时,我发现我的StringEntity的值不是字节数组[123。 43, 234 ...... even though I have confirmed that my string sJSONOut is correctly formatted json.
43,234 ......即使我已经确认我的字符串sJSONOut的格式正确为json。
Another answer here suggested removing BodyStyle = WebMessageBodyStyle.WrappedRequest from the WCF method header. 这里的另一个答案建议从WCF方法标头中删除BodyStyle = WebMessageBodyStyle.WrappedRequest。 That gave me the clue I needed to change that line from WrappedRequest to Bare which is what ended up working.
这为我提供了将那条线从WrappedRequest更改为Bare所需的线索,这最终起作用了。
BodyStyle = WebMessageBodyStyle.Bare BodyStyle = WebMessageBodyStyle.Bare
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.