I am new to user java to connect to server. I have succeed in forming a json which has some key and value to form the body to call the api service and get successful response (with the following code). My questions are:
- Some of my web service just request header info, for example, I just need to put the ApiKey(key name) and key value in the header and send to server, no other info is needed in body, how can I do this?
Some of my web service require both header info and body info, how can I construct the json and send to server? try {
String input = jsonString; URL url = new URL("https://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); System.out.println("errorcode" + conn.getResponseCode()); if (conn.getResponseCode() != 200) { JOptionPane.showMessageDialog(new JFrame(), "Please input a correct username or password"); return; } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String jsonText = read(br); System.out.println("jsonText: " + jsonText);