Walter Taus Walter Taus - 22 days ago 6
Java Question

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.

Answer

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