0

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:

  1. 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?
  2. 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);
    
user207421
  • 305,947
  • 44
  • 307
  • 483
mt73564
  • 11
  • 1
  • possible duplicate https://stackoverflow.com/questions/12732422/adding-header-for-httpurlconnection – Scary Wombat Jul 07 '17 at 04:57
  • You have solution in your code itself, learn more about HttpURLConnection.setRequestProperty https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#setRequestProperty(java.lang.String,%20java.lang.String) – sanoj mathew Jul 07 '17 at 05:00
  • Possible duplicate of [Adding header for HttpURLConnection](https://stackoverflow.com/questions/12732422/adding-header-for-httpurlconnection) – P.J.Meisch Jul 07 '17 at 07:14
  • @Scar I have read that post before, and I got some error when I modify the code SEVERE: null java.lang.RuntimeException: Request Failed. HTTP Error Code: 411 – mt73564 Jul 07 '17 at 08:49

0 Answers0