【问题标题】:Android retrieve return value from WCFAndroid 从 WCF 检索返回值
【发布时间】:2012-03-12 15:45:47
【问题描述】:

我有一个 Android 应用程序,它通过下面的代码发布到网络服务,并且一切正常。但是服务中的 myContract 方法返回一个布尔值,true 或 false。如何检索该值,以便我可以告诉我的应用程序是否继续前进?

HttpPost request = new HttpPost(SERVICE_URI + "/myContract/someString");

request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

编辑

抱歉编辑,但使用 HttpResponse,然后记录或烘烤 response.toString() 返回一个我不明白的字符串!

更新

感谢谢里夫,

但这似乎有点太多的信息和代码来做我想做的事情。我在下面添加了一些有效的代码,但我不确定它是否正确。该服务将返回一个关于 POST 是否成功的布尔值 true 或 false,但我似乎将其作为字符串检索!

HttpEntity responseEntity = response.getEntity();

char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();       
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();

JSONObject jsonResponse = new JSONObject(new String(buffer));        
String ServiceResponse = jsonResponse.getString("putCommuniqueResult");

Log.d("WebInvoke", "Saving : " + ServiceResponse);

这样好吗?它有效,但我不确定它是否正确! 干杯, 迈克。

【问题讨论】:

  • Web 服务旨在能够与所有编程语言进行通信,除非您使用相同的技术来读取 (.NET),否则您将始终读取为字符串并将其解析为您需要的目标格式, 即 C# 可以添加 Web 服务引用,您将获得所需格式的数据,但在任何其他语言中,除非您获得解析 wsdl 然后将 wcf 字符串解析为实际输出的库,否则它将始终是字符串,直到您解析它

标签: android wcf


【解决方案1】:
private static String getDataFromXML(final String text) {
    final String temp = new String(text).split("<")[2].split(">")[1];
    final String temp2 = temp.replace("&lt;", "<").replace("&gt;", ">")
            .replace("&amp;", "&");
    return temp2;
}

/**
 * Connects to the web service and returns the pure string returned, NOTE:
 * if the generated url is more than 1024 it automatically delegates to
 * connectPOST
 * 
 * @param hostName
 *            : the host name ex: google.com or IP ex:
 *            127.0.0.1
 * @param webService
 *            : web service name ex: TestWS
 * @param classOrEndPoint
 *            : file or end point ex: CTest
 * @param method
 *            : method being called ex: TestMethod
 * @param parameters
 *            : Array of {String Key, String Value} ex: { { "Username",
 *            "admin" }, { "Password", "313233" } }
 * @return the trimmed String received from the web service
 * 
 * @author Shereef Marzouk - http://shereef.net
 * 
 * 
 */
public static String connectGET(final String hostNameOrIP,
        final String webService, final String classOrEndPoint,
        final String method, final String[][] parameters) {
    String url = "http://" + hostNameOrIP + "/" + webService + "/"
            + classOrEndPoint + "/" + method;
    String params = "";
    if (null != parameters) {
        for (final String[] strings : parameters) {
            if (strings.length == 2) {
                if (params.length() != 0) {
                    params += "&";
                }
                params += strings[0] + "=" + strings[1];
            } else {
                Log.e(Standards.TAG,
                        "The array 'parameters' has the wrong dimensions("
                                + strings.length + ") in " + method + "("
                                + parameters.toString() + ")");
            }
        }
    }
    url += "?" + params;
    if (url.length() >= 1024) { // The URL will be truncated if it is more
                                // than 1024
        return Communications.connectPOST(hostNameOrIP, webService,
                classOrEndPoint, method, parameters);
    }
    final StringBuffer text = new StringBuffer();
    HttpURLConnection conn = null;
    InputStreamReader in = null;
    BufferedReader buff = null;
    try {
        final URL page = new URL(url);
        conn = (HttpURLConnection) page.openConnection();
        conn.connect();
        in = new InputStreamReader((InputStream) conn.getContent());
        buff = new BufferedReader(in);
        String line;
        while (null != (line = buff.readLine()) && !"null".equals(line)) {
            text.append(line + "\n");
        }
    } catch (final Exception e) {
        Log.e(Standards.TAG,
                "Exception while getting " + method + " from " + webService
                        + "/" + classOrEndPoint + " with parameters: "
                        + params + ", exception: " + e.toString()
                        + ", cause: " + e.getCause() + ", message: "
                        + e.getMessage());
        Standards.stackTracePrint(e.getStackTrace(), method);
        return null;
    } finally {
        if (null != buff) {
            try {
                buff.close();
            } catch (final IOException e1) {
            }
            buff = null;
        }
        if (null != in) {
            try {
                in.close();
            } catch (final IOException e1) {
            }
            in = null;
        }
        if (null != conn) {
            conn.disconnect();
            conn = null;
        }
    }

    if (text.length() > 0 && Communications.checkText(text.toString())) {
        final String temp = Communications.getDataFromXML(text.toString());
        Log.i(Standards.TAG, "Success in " + method + "(" + params
                + ") = " + temp);
        return temp;
    }
    Log.w(Standards.TAG, "Warning: " + method + "(" + params + "), text = "
            + text.toString());
    return null;
}

假设这个 url 让你的服务显示它的输出

http://google.com/wcfsvc/service.svc/showuserdata/11949

public boolean isWSTrue() {
    String data = connectGET("google.com",
            "wcfsvc", "service.svc",
            "showuserdata/11949", null);
    if(null != data && data.length() >0)
        return data.toLowerCase().contains("true");
    throw new Exception("failed to get webservice data");
}

注意:在这种情况下,您实际上不需要解析 JSON 或 XML,如果只检查布尔值,那么您知道如果您发现为真,则为真,如果发现其他任何内容,则为假。

如果您需要使用 XML 或 JSON 获取数据,您可以参考这个答案https://stackoverflow.com/a/3812146/435706

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多