【问题标题】:Consume C# REST service with Java client使用 Java 客户端使用 C# REST 服务
【发布时间】:2017-03-31 20:50:28
【问题描述】:

我有以下 C# REST 服务定义

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "books/{isbn}")]
void CreateBook(string isbn, Book book);

我想从 Java 客户端使用此服务。

    String detail = "<Book><Autor>" + autor + "</Autor><ISBN>" + isbn + "</ISBN><Jahr>" + jahr + "</Jahr><Titel>" + titel + "</Titel></Book>";
    URL urlP = new URL("http://localhost:18015/BookRestService.svc/books/" + isbn);
    HttpURLConnection connectionP = (HttpURLConnection) urlP.openConnection();
    connectionP.setReadTimeout(15*1000);
    connectionP.setConnectTimeout(15*1000);
    connectionP.setRequestMethod("POST");
    connectionP.setDoOutput(true);
    connectionP.setRequestProperty("Content-Type", "application/xml"); 
    connectionP.setRequestProperty("Content-Length", Integer.toString( detail.length() )); 
    OutputStream os = connectionP.getOutputStream();
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
    pw.println(detail);
    pw.flush();
    pw.close();
    int retc = connectionP.getResponseCode();
    connectionP.disconnect();

服务向我的 Java 客户端返回 400。从 C# 客户端调用时,相同的服务可以正常工作。

【问题讨论】:

  • 400 意味着一个错误的请求 - 但通常服务器会告诉你它有什么问题(格式错误的 XML、缺少标头等)。所以很高兴看到状态行和响应的正文内容。此外,使用实际的休息客户端可能有助于理解这个问题。 (弹簧架模板,cxf,...)
  • 要完成@JoeriHendrickx 的回答,我想说您有两个客户的不同响应,原因很简单:您发送的请求不同。您可以使用requestb.in 等工具来分析两个客户端实际发送的http 请求,看看有什么不同。您也可以在此处发布结果。

标签: java c# wcf-rest


【解决方案1】:

我认为您写入流的方式可能是原因,试试这个:

connectionP.setDoOutput(true);
DataOutputStream out = new DataOutputStream(connectionP.getOutputStream());
out.writeBytes(detail);
out.flush();
out.close();

【讨论】:

    【解决方案2】:

    在您的服务器代码中,您使用 UriTemplate = "books/{isbn} 作为 URI 模板,但您的客户端代码将 URI 指定为 "http://localhost:18015/BookRestService.svc/booksplain/" + isbn

    也许您只需要更改 Java 代码中的 URI 以反映服务器 URI,例如“books”而不是“booksplain”"http://localhost:18015/BookRestService.svc/books/" + isbn

    另外,如果您有兴趣使您的代码更简洁,请考虑使用Spring RestTemplate 进行 REST API 调用。

    【讨论】:

    • 感谢您指向书籍与书本。这是一个错字。我实际上用书籍尝试过,但它不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多