Hello, i want to understand these methods as a programmer. The only difference i know is that "get" sends the parameters via the url while "post" does not.
But what actually happens in the source code? How can i implement it?

I found some source code concerning the post method but i don't see it doing something practical. Would someone explain to me what i'm missing?

public static void postData(Reader data, URL endpoint, Writer output) throws Exception {
        HttpURLConnection urlc = null;
        try {
            urlc = (HttpURLConnection) endpoint.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

            OutputStream out = urlc.getOutputStream();

            try {
                Writer writer = new OutputStreamWriter(out, "UTF-8");
                pipe(data, writer);
                writer.close();
            } catch (IOException e) {
                throw new Exception("IOException while posting data", e);
            } finally {
                if (out != null) {
                    out.close();
                }
            }

            InputStream in = urlc.getInputStream();
            try {
                Reader reader = new InputStreamReader(in);
                pipe(reader, output);
                reader.close();
            } catch (IOException e) {
                throw new Exception("IOException while reading response", e);
            } finally {
                if (in != null) {
                    in.close();
                }
            }

        } catch (IOException e) {
            throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
        } finally {
            if (urlc != null) {
                urlc.disconnect();
            }
        }
    }

    /**
     * Pipes everything from the reader to the writer via a buffer
     */
    private static void pipe(Reader reader, Writer writer) throws IOException {
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            writer.write(buf, 0, read);
        }
        writer.flush();
    }

I did managed to implement the "get" method. But i'm not to sure it's done the right way. All i get as a response is the full text file from the server. Please check if it's the way to be done

private String sendGetRequest(String endpoint, String requestParameters) {
        String result = null;
        if (endpoint.startsWith("http://")) {
   // Send a GET request to the servlet
            try {
// Construct data
                StringBuffer data = new StringBuffer();

// Send data
                String urlStr = endpoint;
                if (requestParameters != null && requestParameters.length() > 0) {
                    urlStr += "?" + requestParameters;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();

// Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line);
                }
                rd.close();
                result = sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

Dani AI

Generated

Short conceptual answer tied to the thread: the visible difference (query string vs body) is only part of it. GET and POST carry different intent, are handled differently by caches, browsers and servers, and require different headers/encoding. was correct about intent; is right that form-style POST bodies commonly look like name=value&name=value. The practical gaps in the example posted by are about charset symmetry, error handling, and a few HttpURLConnection behaviors that commonly trip people.

Practical implementation notes and common pitfalls

  • Always set the correct Content-Type and a charset, and use the same charset when writing the request body and when constructing readers for the response (InputStreamReader with UTF-8).
  • HttpURLConnection: call setDoOutput(true) before writing the body; calling getOutputStream() implicitly connects. For large bodies consider setFixedLengthStreamingMode(length) to avoid buffering everything in memory.
  • Always check the response code (getResponseCode()). On 4xx/5xx, getInputStream() throws; use getErrorStream() to read server error text. Log response headers (Content-Type, Content-Disposition) to understand why the server returned a file or different content.
  • Security: POST does not hide data from network logs or intermediaries. Use HTTPS for sensitive data. Query strings end up in browser history and referer headers.

Example (build a form-encoded body and send with Java 11 HttpClient)

String form = "a=" + URLEncoder.encode("one", StandardCharsets.UTF_8)
            + "&b=" + URLEncoder.encode("two", StandardCharsets.UTF_8);

HttpRequest req = HttpRequest.newBuilder()
    .uri(URI.create("https://example.com/endpoint"))
    .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
    .POST(BodyPublishers.ofString(form))
    .build();

HttpResponse<String> resp = HttpClient.newHttpClient()
    .send(req, BodyHandlers.ofString(StandardCharsets.UTF_8));
int status = resp.statusCode();
String body = resp.body();

Quick troubleshooting checklist

  • Compare declared charset with actual InputStreamReader charset.
  • Inspect response code and headers before assuming body contents.
  • If POST seems ignored, confirm server expects form-encoded vs XML/JSON and set Content-Type accordingly.
  • For repeatable calls prefer GET for safe/idempotent reads; use POST/PUT/PATCH for state changes.

Recommended Answers

All 3 Replies

With a post requet you simple feed the var=value&var=value String through into the output stream.

I am sorry for posting to this thread since I don't have anything new to add but I can't help to notice that you both have been down voted.
Congratulations.
Yet another post where someone, anonymous, decided for no reason and explanation, that an interesting question and a good answer should be down voted.

Looks like that the voting system is being repeatedly abused

commented: Amen. +4

There is an important philosophical difference, and one that most people don't realise.
Those same people don't realise that GET and POST are actually not all the possible http request methods, there are several others!

GET is intended for requesting data from the webserver.
POST is intended for submitting data TO the server to do something with.
Of course to request information requires sending information, and submitting information usually leads to the returning of more information as a result, blurring the distinction to an extent.

In general, using POST in combination with request forwarding (rather than redirection) causes cleaner URLs and shorter browser history when using html forms.
Some people also use it as an (ill conceived) security system as the request parameters aren't shown in the URL and thus they (incorrectly) think users can't see such things as cleartext passwords sent in the request.

commented: extremely informative. +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.