How to send json string to .NET REST service from java?

I am trying to send a json string from my android client to my .net Rest service ... can anyone help me with 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);

The answer is a bad request. Am I sending a json object as a string? Is this code correct?

+3
source share
3 answers

decision

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

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

+7
source

For those who have the same problem, here's a quick fix: - The web service expects an object that includes a property of type String. To do this, you must have a DataContract of the "expected" object.

, :

[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

It looks correct, except for the following header:

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

Content encoding is described here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5

0
source

Source: https://habr.com/ru/post/1771682/


All Articles