开发者

how to send a json string to a .NET REST service from java?

开发者 https://www.devze.com 2023-01-22 08:32 出处:网络
i am trying to send a json string from my android client to my .net Rest service... can anyone help me开发者_开发百科 in this issue?

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

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


the solution is

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 json object string, so in .net the request should have object parameter...


For anyone having the same issue, here's a quick fix: - The webservice is expecting an object which includes a property of type String. In order to make this work, you must have a DataContract of the "expected" object.

For example, instead of asking for a string, create a class for your data:

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

So, in your WCF method declaration you would have:

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

In you Java side, you have:

JSONStringer json = new JSONStringer().object().key("MyString").value("Hello!").endObject();


Looks valid except the following header:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消