【问题标题】:WCF service always returns random numbers in the response bodyWCF 服务始终在响应正文中返回随机数
【发布时间】:2016-08-02 21:14:49
【问题描述】:

我有一个用 C# 编写的 WCF 服务:

namespace MyServices
{
    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/foo/{param}")]
        string foo(string param);
    }
}

public class MyService : IMyService
{
    public string foo(string param)
    {
        //Do stuff with param
        return "Some processed data";
    }
}

每当我使用此服务时,它都可以正常工作,除了响应中的每一行总是前面有一个数字(有时是一个带有字符的数字)。最后一行总是一个 0。

下面是一个使用 Java 编写的使用此服务的客户端:

public class Main
{
    public static void main(String[] args)
    {
        try 
        {
            Socket soc = new Socket(InetAddress.getByName("<SOME IP ADDRESS>"), 80);
            PrintWriter out = new PrintWriter(soc.getOutputStream());
            String headers = "GET /MyService.svc/foo/some_data HTTP/1.1\r\n"
                             + "Host: <SOME HOST>\r\n"
                             + "Content-Type: text/plain;charset=utf-8\r\n"
                             + "Content-Length: 0\r\n\r\n";

            out.print(headers);
            out.flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
            String response;

            while((response = in.readLine())!=null)
            {
                //Do something with the response            
                System.out.println(response);
            }
            out.close();
            soc.close();
        catch (UnknownHostException e) 
        {
            System.err.println(e.getMessage());
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

这将输出以下内容:

HTTP/1.1 200 OK
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/plain;charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=2e5dd814a4cb78f8a5825d56c5879cd18fa384d20597b10f3c685ffe2cff1f53;Path=/;Domain=<SOME DOMAIN NAME>
Date: Tue, 02 Aug 2016 22:53:25 GMT

15
"Some processed data"
0

起初我以为数字代表下一行中的字符数,0表示消息体的结尾,但似乎并非如此。

感谢您的帮助,谢谢:)

【问题讨论】:

    标签: java c# rest wcf


    【解决方案1】:

    这是因为传输编码是分块的 (https://en.wikipedia.org/wiki/Chunked_transfer_encoding)。 15 是 HEX 表示这个块中的 21 个字符,其中 0 作为结束标记。

    【讨论】:

    • 啊,是的,现在说得通了,我将添加处理传输编码的功能。谢谢
    • 你为什么不使用 Java.net.HttpURLConnection 呢?它将为您处理编码器模式和连接等细节。
    • 是的,我最终改用了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2018-07-16
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多