0

我有如下样品要求:

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

我如何执行此请求以获得响应?谢谢!

4

1 回答 1

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;
    }
于 2012-09-25T01:58:51.587 回答