从Android Java项目中调用Rest Service
问题描述:
我想调用用WCF编写的rest服务,并且输入的类型为Composite,这意味着.net的用户类对象的用户类对象示例如下所示:
I want to call a rest service which is written in WCF and the input is of type composite which means user class object of .net example of the user class object is as shown below:
public class Sub
{
public string HostUID { get; set; }
public string HostName { get; set; }
}
so the rest service method input is as below:
[OperationContract(Name="SampleSUb")]
[WebInvoke(UriTemplate = "/Subsc", Method = "GET")]
public string Method1(Sub input);
现在,我想从android java应用程序调用method1 rest服务.我能够连接到Rest服务,但不能将输入参数发送到Sub class.
有人可以帮我吗?
Now i want to call the method1 rest service from android java application. I am able to connect to the Rest service but not able to send the input parameters to Sub class.
Can any one help me on this???
答
只需通过以下JSON方法从android
进行调用
WCF服务方法声明
Just need to call by using JSON method as below from android
WCF service method Declaration
public class Sub
{
public string HostUID { get; set; }
public string HostName { get; set; }
}
因此,其余服务方法的输入如下:
so the rest service method input is as below:
[OperationContract(Name="SampleSUb")]
[WebInvoke(UriTemplate = "/Subsc", Method = "GET",RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json))]
public string Method1(Sub input);
Android Java代码:
Android Java code:
URI uri = new URI("http://.............");
JSONObject jo1 = new JSONObject();
jo1.put("Id", "12");
jo1.put("StringValue", "as");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("User-Agent", "Pigeon");
conn.setChunkedStreamingMode(0);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(jo1.toString().getBytes());
out.flush();
int code = conn.getResponseCode();
String message = conn.getResponseMessage();
InputStream in1 = conn.getInputStream();
StringBuffer sb = new StringBuffer();
String reply1;
try { int chr; while ((chr = in1.read()) != -1) { sb.append((char) chr); }
reply1 = sb.toString(); }
finally { in1.close(); }