Android 通过Post方式提交数据
关键代码:
public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{ // title=dsfdsf&timelength=23&method=save StringBuilder sb = new StringBuilder(); if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), enc)).append('&'); } sb.deleteCharAt(sb.length()-1); } //得到实体的二进制数据,以便计算长度 byte[] entitydata = sb.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据 //Content-Type: application/x-www-form-urlencoded //Content-Length: 38 //下面的两个属性是必须的 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length)); //传递数据的长据 OutputStream outStream = conn.getOutputStream(); outStream.write(entitydata); //把内存中的数据刷新输送给对方 outStream.flush(); outStream.close(); //获取服务端的响应,200代表成功 if(conn.getResponseCode()==200){ return true; } return false; }
主要是仿照IE浏览器的Http协议,可以通过HttpWatch Professional这个插件查看IE浏览器提交数据的后台实现原理。
更多相关文章
- Android获取浏览器User Agent
- 判断微信内置浏览器, 其他浏览器
- android将对象写入文件和从文件中读取对象数据
- android 向SD卡写入数据
- Android之常见数据类型
- 关于 SQLiteOpenHelper 的自创建数据库目录文件
- Android自制浏览器WebView-android学习之旅(64)
- Android判断上网方式(Wifi还是数据流量)