简体   繁体   中英

Consume C# REST service with Java client

I have following C# REST service definition

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

I want to consume this service from a Java client.

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

The service returns 400 to my Java client. The same service works fine when called from a C# client.

I think that way you write to the stream may be the reason, try this:

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

In your server code you use UriTemplate = "books/{isbn} as URI template, but your client code specifies the URI as "http://localhost:18015/BookRestService.svc/booksplain/" + isbn .

Maybe you only need to change the URI in Java code to reflect the server URI, for example "books" instead of "booksplain" "http://localhost:18015/BookRestService.svc/books/" + isbn .

Also, if you are interested in making your code cleaner and more concise, consider using Spring RestTemplate for making REST API calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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