如何使用Http连接android请求POST

时间:2012-09-25 01:29:45

标签: android http httpurlconnection

我有以下示例请求:

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

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

1 个答案:

答案 0 :(得分:3)

使用它:

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;
    }