zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

[android] 采用post的方式提交数据详解手机开发

Android数据手机开发 详解 方式 提交 采用
2023-06-13 09:20:13 时间

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 "请求失败"; 

 }

 

5478.html

app程序应用开发手机开发无线开发移动端开发