public boolean post(String username, String password) throws Exception { username = URLEncoder.encode(username);// 中文数据需要经过URL编码 password = URLEncoder.encode(password); String params = "username=" + username + "&password=" + password; byte[] data = params.getBytes(); URL url = new URL(address); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(3000); //这是请求方式为POST conn.setRequestMethod("POST"); //设置post请求必要的请求头 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 请求头, 必须设置 conn.setRequestProperty("Content-Length", data.length + "");// 注意是字节长度, 不是字符长度 conn.setDoOutput(true);// 准备写出 conn.getOutputStream().write(data);// 写出数据 return conn.getResponseCode() == 200; }