您的位置:首页 > 移动开发 > Android开发

android 通过post方式提交数据的最简便有效的方法

2015-06-02 13:55 381 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: