HttpURLConnection--HttpURLConnection的Post请求方式

来源:互联网 发布:数据透视表值字段设置 编辑:程序博客网 时间:2024/05/16 17:43
/** * 使用post的方式登录 * @param userName * @param password * @return */public static String loginOfPost(String userName, String password) {HttpURLConnection conn = null;try {URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet");conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setConnectTimeout(10000); // 连接的超时时间conn.setReadTimeout(5000); // 读数据的超时时间conn.setDoOutput(true);// 必须设置此方法, 允许输出//conn.setRequestProperty("Content-Length", 234);// 设置请求头消息, 可以设置多个// post请求的参数String data = "username=" + userName + "&password=" + password;// 获得一个输出流, 用于向服务器写数据, 默认情况下, 系统不允许向服务器输出内容OutputStream out = conn.getOutputStream();out.write(data.getBytes());out.flush();out.close();int responseCode = conn.getResponseCode();if(responseCode == 200) {InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {Log.i(TAG, "访问失败: " + responseCode);}} catch (Exception e) {e.printStackTrace();} finally {if(conn != null) {conn.disconnect();}}return null;}

0 0
原创粉丝点击