Reputation: 814
I have to write the most basic POST client in Java. It sends a few parameters to a Certificate server. The parameters are supposed to be JSON encoded
I have the attached code, how do I make the params JSON encoded?
String url = "http://x.x.x.x/CertService/revoke.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "serialnumber=C02G8416DRJM&authtoken=abc&caauthority=def&reason=ghi";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Upvotes: 0
Views: 37
Reputation: 711
Can you just set your content type as application/json and send the json string?
con.setRequestProperty("Content-Type", "application/json");
Upvotes: 1
Reputation: 572
The text you're POSTing in your example looks like it's application/x-www-form-urlencoded. To get application/json encoding, prepare the parameters as a map, then use any of several JSON encoding libraries (e.g., Jackson) to convert it to JSON.
Map<String,String> params = new HashMap<>();
params.put("serialnumber", "C02G8416DRJM");
params.put("authtoken", "abc");
...
ObjectMapper mapper = new ObjectMapper();
OutputStream os = con.getOutputStream();
mapper.writeValue(os, params);
os.flush();
os.close();
...
Upvotes: 0