我使用服务合同制作了一个休息网络服务,如下所示
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "postdataa?id={id}"
)]
string PostData(string id);
PostData方法的实现
public string PostData(string id)
{
return "You posted " + id;
}
Android中的代码,用于在网络服务中发布数据
HttpClient httpclient = new DefaultHttpClient();
HttpHost target = new HttpHost("192.168.1.4",4567);
HttpPost httppost = new HttpPost("/RestService.svc/postdataa?");
String result=null;
HttpEntity entity = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", "1"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(ent);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(target, httppost);
entity = response.getEntity();
//get xml result in string
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
问题是xml结果显示且缺少参数值:
<PostDataResponse xmlns="http://tempuri.org/"><PostDataResult>You posted </PostDataResult></PostDataResponse>
我不知道出了什么问题。
答案 0 :(得分:0)
由于您正在使用REST服务,请尝试一下:
private static char[] GetData(String servicePath) throws Exception
{
InputStream stream = null;
String serviceURI = SERVICE_URI;//this is your URI to the service
char[] buffer = null;
try
{
if (servicePath != "")
serviceURI = serviceURI + servicePath;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(serviceURI);
request.setHeader("Accept", "application/xml");
request.setHeader("Content-type", "application/xml");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
// Read response data into buffer
buffer = new char[(int)responseEntity.getContentLength()];
stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
}
}
catch (Exception e)
{
Log.i("Survey Application", e.getMessage());
throw e;
}
return buffer;
}
使用
调用此方法try
{
char[] buffer = GetData("postdataa/" + id);
if (buffer != null)
//Build your XML object
}
catch (Exception e)
{
}