繁体   English   中英

通过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();

该服务将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调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM