一、权限
<uses-permission android:name="android.permission.INTERNET"/>
二、代码
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();
if(conn.getResponseCode()==200){
return true;
}
return false;
}