我在我的机器上有一个简单的WCF Web服务,我开发这个服务来服务Android和IOS设备。Android HttpPost失败 - 服务器接收空查询字符串参数
服务有一个方法如下:
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/?message={message}")]
string ServiceMessage(string message);
我有3个客户,一个.NET测试客户端使用的HttpWebRequest工作正常,一个IOS客户端的正常工作和一个Android客户端,我已经开发与HttpPost和HttpClient类失败。
使用招反向代理我已经调试.NET客户端的输出:
POST http://127.0.0.1:8888/Service1.svc/?message=_|JSON MESSAGE BODY|_HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: 127.0.0.1:8888
Content-Length: 338
Expect: 100-continue
Connection: Keep-Alive
_|JSON MESSAGE BODY|_
在另一方面,这是Android HTTP后的输出:
POST http://10.0.2.2:8888/Service1.svc/ HTTP/1.1
Content-Type: application/json; charset=utf-8
Content-Length: 139
Host: 10.0.2.2:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
Expect: 100-Continue
message=_|JSON MESSAGE BODY|_
正如你可以看到,.Net将邮件中的邮件参数放在顶部,而不是 将邮件变量名称放在底部,而Android不会将邮件正文放在邮政顶部,并且将邮件变量名称放在底部。
这是我的Android邮编,
HttpPost httpPost = new HttpPost(url);
String messageBody = "message=" + jsonMessageParameter;
StringEntity entity = new StringEntity(messageBody);
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse response = hc.execute(httpPost);
InputStream content = response.getEntity().getContent();
String json = ConvertStreamToString(content);
当使用此代码调用,服务器方法被调用,但该消息的方法参数为null。 我试着玩Uri.Builder类也让android的帖子把邮件放在标题上,但不起作用。 如果有人可以帮我解决问题,我会在这几个小时内困住这个小时。
谢谢你在前进,
詹姆斯
编辑:
我改变了Android代码:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("message", jsonMessageParameter));
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity urlEncodedFromEntity = new UrlEncodedFormEntity(
nameValuePairs);
urlEncodedFromEntity.setContentType(new BasicHeader("Content-Type",
"application/json; charset=utf-8"));
httpPost.setEntity(urlEncodedFromEntity);
InputStream postStream = httpPost.getEntity().getContent();
String postOutput = ConvertStreamToString(postStream);
HttpResponse response = hc.execute(httpPost);
InputStream content = response.getEntity().getContent();
String json = ConvertStreamToString(content);
不过还是提琴手监控如下:
POST http://10.0.2.2:8888/Service1.svc/ HTTP/1.1
Content-Length: 189
Content-Type: application/json; charset=utf-8
Host: 10.0.2.2:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
Expect: 100-Continue
message=_|MESSAGE_JSON|_
但是如果服务方法接收到多个查询字符串参数会怎么样呢? – 2012-04-22 15:16:04
使用UrlEncodedFormEntity而不是StringEntity,它会产生一个像param1 = value1&param2 = value2的主体...... – Venator85 2012-04-22 18:41:08
最后,似乎我没有在服务器端读取JSON。 对我而言,唯一的方法是在服务器端接收Stream对象,这使我可以阅读消息正文。 – 2012-05-08 16:20:21