ZimZim
ZimZim

Reputation: 3381

What do I write with outputstream in Java if I want to send an http request?

So I have this piece of code, and let's assume I'm filling out a form on a website and want to submit it, how do I find the keys and values to submit? I'll explain better, I have this code, it's supposed to send an HTTP POST Request, but I have no idea what to put in place of the "key1" and "value1", same goes with "key2" and "value2":

public String sendPostRequest(String url) {

    StringBuffer sb = null;

    try {
        String data = URLEncoder.encode("key1", "UTF-8") + "="
                + URLEncoder.encode("value1", "UTF-8");
        data += "&" + URLEncoder.encode("key2", "UTF-8") + "="
                + URLEncoder.encode("value2", "UTF-8");

        URL requestUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) requestUrl
                .openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

        OutputStreamWriter osw = new OutputStreamWriter(
                conn.getOutputStream());
        osw.write(data);
        osw.flush();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));

        String in = "";
        sb = new StringBuffer();

        while ((in = br.readLine()) != null) {
            sb.append(in + "\n");
        }

        osw.close();
        br.close();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return sb.toString();
}

Can you give me an example site with the working replica of this code? (key1/key2 and value1/value2 replaced with something that works)

You can add more keys/values if that works better, I just have no idea how to know what to fill in there for every different site.

Upvotes: 1

Views: 2826

Answers (1)

Skip Head
Skip Head

Reputation: 7760

The keys would be the name attributes of the input elements of the html form. The values would be the values you want to set.

Upvotes: 3

Related Questions