0

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

2 Answers 2

1

Can you just set your content type as application/json and send the json string?

con.setRequestProperty("Content-Type", "application/json"); 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.