Reputation: 1025
I have 2 web services -
1) http://address.to.web.service/product/getProductById?productId=1000
2) http://address.to.web.service/product/updateProduct
The first one gets the product while the other one updates it.
the updateService takes input as a json -
{
"productId" : 1,
"productName" : "XYZ",
"Price": "$25.00"
}
I tested both the urls using Postman and works fine.
Being new to web service, I want to know what is the best way to pass a parameter to the webservice.
Is passing JSON similar to passing an integer value?
Upvotes: 1
Views: 454
Reputation: 4934
So far, I cannot tell you how to archive that using java, but you can try using curl:
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"productId" : 1, "productName" : "XYZ", "Price": "$25.00"}' http://address.to.web.service/product/updateProduct
As you can see, you have to specify you are going to send json
content and also the HTTP method (POST to create resources).
PS. Try PATCH to update.
edit
I've done that, first you need to import the required classes:
import java.net.HttpURLConnection;
import java.io.DataOutputStream;
import java.net.URL;
with this method:
try {
URL url = new URL("http://address.to.web.service/product/updateProduct");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes("{\"productId\" : 1, \"productName\" : \"XYZ\", \"Price\": \"$25.00\"}");
out.flush();
out.close();
} catch (Exception e) {
System.out.println(e.toString());
}
Upvotes: 1
Reputation: 43117
For calling a web service from Java, try the RestTemplate from Spring, described in their step by step tutorial.
Upvotes: 1