0

I have sample request as below:

POST /api/something.php HTTP/1.1
Host: test.com
Accept-Charset: UTF-8
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded;
Content-type: text/plain; charset=UTF-8
Content-length: 64

// Some parameters are here

How I can execute this request to get respond? Thanks!

Kingfisher Phuoc
  • 7,392
  • 8
  • 43
  • 75
  • 1
    this may help you http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests – Sudar Nimalan Sep 25 '12 at 01:42

1 Answers1

3

use this :

String responseFromServer = startUrlConnection("http://test.com/api/something.php", "username=testing&password=123");

-

private String startUrlConnection(String targetURL, String urlParameters) throws IOException {

        URL url;
        connection = null;
        String output = null;
        try {
            // Create connection
            url = new URL(targetURL);

            System.setProperty("javax.net.debug", "all");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            // Send request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            // Get Response
            InputStream is;

            if (connection.getResponseCode() <= 400) {
                is = connection.getInputStream();
            } else {
                /* error from server */
                is = connection.getErrorStream();
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();

            output = response.toString();
        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
        return output;
    }
HelmiB
  • 12,025
  • 5
  • 38
  • 65
  • I don't see the use of `Accept-Charset: UTF-8 Connection: keep-alive Content-Type: application/x-www-form-urlencoded; Content-type: text/plain; charset=UTF-8 Content-length: 64 ` Can you explain what's above block? And what's purpose?! Thanks!! – Kingfisher Phuoc Sep 25 '12 at 03:21