Reputation: 8519
I'm learning about JAX-RS and Jersey. I am trying to post data to a URL however I have an issue I do not know to fix:
Form formData = new Form();
formData.param("merchant_id", mPayment.getMerchantId());
formData.param("transaction_id", mPayment.getTransactionId());
formData.param("code", mPayment.getCode());
formData.param("amount", String.valueOf(mPayment.getAmount()));
formData.param("desc", mPayment.getDesc());
formData.param("phone", mPayment.getPhone());
Response response = target.path("process").request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.form(formData));
Now everything works well when it's just a string however the server is expecting a float data type for the field amount however when I try to use it without String.valueOf()
I get an error. How do I add params with different data types so I can post?
Upvotes: 2
Views: 8440
Reputation: 173
You cannot maintain the type information across the call to the server. The form data will be transferred as text with the application/x-www-form-urlencoded content type header, this is why the Form class accepts String parameter values (similarly to how you could only enter text values in a browser form).
So your code should be sufficient. At the server side, you can declare the parameter as a float and annotate it with javax.ws.rs.FormParam. If the parameter cannot be cast to the desired (float) type by the Jersey runtime, it will return a 400 BAD REQUEST.
In a nutshell:
Use server code similar to:
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("/service")
public class myService {
@POST
public Response addOrder(
@FormParam("merchant_id") String merchant_id,
@FormParam("amount") float amount
// more parameters
) {
return Response.ok().build();
}
}
Upvotes: 1