2015年5月21日 星期四

【Android】HttpURLConnection Post 方法


    public static String excutePost(String targetURL, String urlParameters) {
        URL url;
        HttpURLConnection conn = null;


        try {
            //Create connection
            url = new URL(targetURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            conn.setRequestProperty("Content-Length", "" +
                    Integer.toString(urlParameters.getBytes().length));
            conn.setRequestProperty("Content-Language", "en-US");

            conn.setUseCaches(false);     // Post cannot use caches
            conn.setDoInput(true);        // Read from the connection. Default is true.


            // Output to the connection. Default is false, set to true because post
            // method must write something to the connection
            conn.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(
                    conn.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            //Get Response
            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            reader.close();

            return response.toString();

        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (conn != null) {
                conn.disconnect();
            }
        }
    }

沒有留言:

張貼留言