簡體   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