如何发送一个JSON字符串从Java中的.NET REST服务?字符串、JSON、Java、REST

2023-09-05 09:52:23 作者:华山论贱

我想从我的Andr​​oid客户端发送一个JSON字符串到我的.NET REST服务... 谁能帮助我在这个问题上?

i am trying to send a json string from my android client to my .net Rest service... can anyone help me in this issue?

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对象为字符串?这是code正确吗?

Response is bad request. am i sending the json object as string? is this code correct?

推荐答案

解决的办法是

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的要求应该有对象参数...

This will send json object string, so in .net the request should have object parameter...