注意:post提交实体部分必须单独发送,而且要设置允许对外输出conn.setDoOutput(true);
get方式提交数据给服务器
第一步:在AndroidManifest.xml中加入仿问internet的权限
<uses-permission android:name="android.permission.INTERNET"/>
第二步:构造实体部分即要发送数据到服务器的参数值
如:要发送name=xjz age=23
远程服务器path路径:http://218.67.59.224:8080/test/
则构造实体部分:
StringBuilder sb = new StringBuilder(path);
sb.append('?');
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);
构造之后的URL为http://218.67.59.224:8080/test/?name=xjz&age=23
第三步:构造完URL之后,设置请求头,并提交到服务器
URL url = new URL(sb.toString());
//提交到服务器,服务器可以通过参数值进行获取值
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
Post方式提交数据给服务器
第一步:在AndroidManifest.xml中加入仿问internet的权限
<uses-permission android:name="android.permission.INTERNET"/>
第二步:构造实体部分即要发送数据到服务器的参数值
如:要发送name=xjz age=23
远程服务器path路径:http://218.67.59.224:8080/test/
则构造实体部分:
StringBuilder sb = new StringBuilder();
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append('=')
.append(URLEncoder.encode(entry.getValue(), enc)).append('&');
}
第三步:设置请求头部分
byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
//如果通过post提交数据,必须设置允许对外输出数据
conn.setDoOutput(true);
//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));
sb.deleteCharAt(sb.length()-1);
第四步:发送实体部分
OutputStream outStream = conn.getOutputStream();
outStream.write(entitydata);
outStream.flush();
outStream.close();