• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Jax-rs sequence of methods

 
jigar singh
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please help with the following question:

What is the correct sequence of methods that must be added (in line //1 and line //2) in the following JAX-RS client to return a valid result. The request should be a POST request with a String as body.

public static void main(String[] args) throws IOException {
URL restURL = new URL("http://localhost:8080/SimpleRS/math/table/post");
HttpURLConnection connection = (HttpURLConnection) restURL.openConnection();
// 1
connection.connect();
String entity = "5";
// 2
}

Wrong Answer:
Why is this wrong:
Line // 1 connection.setRequestMethod("POST");
connection.setDoOutput(true);
Line // 2
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeChars(entity);
wr.flush(); wr.close();

Correct Answer:
why this is right:
Line // 1
connection.setRequestMethod("POST");
connection.setDoOutput(true);
Line // 2
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(entity);
wr.flush(); wr.close();

 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only difference is the use of writeChars vs. writeBytes. After reading the javadocs of those methods, what would the actual difference be, and how do you think that might matter?
 
jigar singh
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question in Enthuware which asks to send a body as String. Even i am confused.method writeChars will write entity as stream of characters . This is the option I chose and was wrong.

However, method writeBytes will write the entity as stream of bytes. This is the right option as per their question bank. I wanted to know why this is correct option.
 
Himai Minh
Ranch Hand
Posts: 1359
7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you need to write a sequence of bytes over the wire, not a sequence of characters.
 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The important part of the javadoc is "Writes a char to the underlying output stream as a 2-byte value, high byte first." (in the writeChar method). The code doesn't set the encoding, so the platform defauilt encoding is used. But none of the various default encodings used in common JVM platforms (Windows, OS X, Linux) would encode "5" in two bytes, and since the request doesn't set any other encoding, what would arrive at the server would be something other than what was sent.
 
jigar singh
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ulf and Himai
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic