android post方式传递参数并获取返回数据代码

public static String Post(String url,String content) throws IOException {
        String resultData = "";
        URL httpUrl = null;
        try {
            httpUrl = new URL(Constants.HOST+url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (url != null) {
            try {
                HttpURLConnection urlConn = (HttpURLConnection) httpUrl.openConnection();
                urlConn.setDoInput(true);
                urlConn.setDoOutput(true);
                urlConn.setRequestMethod("POST");
                urlConn.setUseCaches(false);
                urlConn.setInstanceFollowRedirects(true);
                urlConn.setRequestProperty("contentType", "utf-8");
                urlConn.connect();
                DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
                Log.i("testPost", "content-->" + content);
                out.writeBytes(content);
                out.flush();
                out.close();
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"));
                String inputLine = null;
                while ((inputLine = reader.readLine()) != null) {
                    resultData += inputLine + "\n";
                }
                reader.close();
                urlConn.disconnect();
                Log.i("testPost", "resultData-->" + resultData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultData;
    }

你可能感兴趣的:(android)