代码之家  ›  专栏  ›  技术社区  ›  Ads

如何将JSON字符串从Java发送到.NETREST服务?

  •  3
  • Ads  · 技术社区  · 14 年前

    我正在尝试将一个JSON字符串从我的Android客户端发送到我的.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对象作为字符串发送?此代码正确吗?

    3 回复  |  直到 14 年前
        1
  •  7
  •   Macabre2077 Ads    12 年前

    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); 
    

        2
  •  2
  •   mimi    14 年前

    [DataContract]
    public class MyJSonString
    {
     [DataMember]
        public String MyString {get;set;}
    }
    

    public void GetMyJsonString(MyJSonString mystring){...}
    

    JSONStringer json = new JSONStringer().object().key("MyString").value("Hello!").endObject();
    
        3
  •  0
  •   jgauffin    14 年前

    str.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json; charset=utf-8"));
    

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5