我正在尝试使用 httpost 从我们的 WCF 网络服务获取数据
如果 webservice 函数没有 params ,类似于 List getAllMessages()
我在 json 中获取列表,这里没问题
棘手的部分是当函数需要获取参数时让我们说 Message getMessage(string id) 在尝试调用此类函数时我得到错误代码 500
工作代码是:
public String GetAllTitles()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/GetAllTitles");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
这段代码非常适合没有参数的函数。我把这段代码改成:
public String SearchTitle(final String id)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/SearchTitle");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json; charset=utf-8");
NameValuePair data = new BasicNameValuePair("id",id);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(data);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
thr webservice 中的函数头是:
[OperationContract]
public TitleResult SearchTitle(string id)
{
Stopwatch sw = LogHelper.StopwatchInit();
try
{
TitleManager tm = new TitleManager();
Title title = tm.TitleById(id);
sw.StopAndLog("SearchTitle", "id: " + id);
return new TitleResult() { Title = title };
}
catch (Exception ex)
{
sw.StopAndLogException("SearchTitle", ex, "id: " + id);
return new TitleResult() { Message = ex.Message };
}
}
任何人都可以看到我错过了什么?
谢谢,我正在为这个而头晕目眩。