Android,HttpPost for WCF

时间:2012-07-03 11:33:04

标签: java android wcf

我正在尝试使用httpost从我们的WCF网络服务中获取数据

如果webservice函数没有params,比如List getAllMessages()

我在json中获取List,这里没问题

棘手的部分是当函数需要获取参数时 假设消息getMessage(字符串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;

}

此代码适用于没有参数的functios .. 我把这段代码改成了:

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

任何人都可以看到我错过了什么?

谢谢,我对这个问题感到失望。

1 个答案:

答案 0 :(得分:0)

列表不是json, 试试

String data = "{ id : \"" + id + "\" }";

不要忘记将Content-Length设置为data.length