我正在尝试从我的Android客户端发送一个json字符串到我的.net Rest服务... 谁能在这个问题上帮助我?
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://myURL");
JSONObject json = new JSONObject();
json.put("name", "i am sample");
StringEntity str = new StringEntity(json.toString());
str.setContentType("application/json; charset=utf-8");
str.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json; charset=utf-8"));
post.setEntity(str);
HttpResponse response = client.execute(post);
响应是不好的请求。我发送json对象作为字符串?这段代码是否正确?
答案 0 :(得分:7)
解决方案是
HttpPost request = new HttpPost("http://10.242.48.54/restinsert/Service1.svc/save");
JSONStringer json = new JSONStringer()
.object()
.key("cname").value(name)
.key("cmail").value(email)
.endObject();
StringEntity entity = new StringEntity(json.toString(), "UTF-8");
entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
这将发送json对象字符串,因此在.net中请求应该有对象参数...
答案 1 :(得分:2)
对于有同样问题的人,这里有一个快速修复: - webservice期望一个包含String类型属性的对象。 为了使其工作,您必须具有“预期”对象的DataContract。
例如,不是要求字符串,而是为数据创建一个类:
[DataContract]
public class MyJSonString
{
[DataMember]
public String MyString {get;set;}
}
因此,在您的WCF方法声明中,您将拥有:
public void GetMyJsonString(MyJSonString mystring){...}
在Java方面,你有:
JSONStringer json = new JSONStringer().object().key("MyString").value("Hello!").endObject();
答案 2 :(得分:0)
看起来有效,但以下标题除外:
str.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json; charset=utf-8"));
内容编码在此处描述:http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5