使用 Java 客户端使用 C# REST 服务

Consume C# REST service with Java client

我有以下 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();

服务 returns 400 到我的 Java 客户。当从 C# 客户端调用时,相同的服务工作正常。

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

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

在您的服务器代码中,您使用 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 调用。