GET:内部实现是组拼Url的方式,http协议规定最大长度4kb,ie浏览器限制1kb
POST和GET的区别比较了一下,多了几条信息
Content-Type:application/x-www-form-urlencoded
Content-Length:93
主体内容
只需修改上一节代码中的几个地方:
调用HttpURLConnection对象的setRequestMethod(“POST”)方法
调用HttpURLConnection对象的setRequestProperty()方法,把上面的几条头信息加进去
拼接好内容比如 String data=”username=”+username,调用String对象的length()方法,返回长度,长度+””空字符串转成String类型
调用HttpURLConnection对象的setDoOutput(true)方法,是否允许写数据
调用HttpURLConnection对象的getOutputStream()方法,获取OutputStream对象
调用OutputStream对象的write(buffer)方法,向服务器写数据,参数:buffer是byte[]数组,调用String对象的getBytes()方法,得到byte[]
service:
/** * POST传递参数 * * @param username * @param password * @return */ public static String loginByPost(String username, String password) { String path = ROOT_PATH; try { URL url = new URL(path); String data="username="+username+"&password="+password; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); //设置头信息 conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length()+""); //写数据 conn.setDoOutput(true); OutputStream os=conn.getOutputStream(); os.write(data.getBytes()); int code = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); String info = StreamTools.readInputStream(is); return info; } } catch (Exception e) { e.printStackTrace(); } return "请求失败"; }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/5478.html