使用HC(HttpClient)/UC(HttpURLConnection)进行网络访问的基本步骤:
0. 申请权限 INTERNET访问权限
1. 任何网络访问的相关代码,必须在工 作线程中执行!
2. 创建HC/UC对象
3. 声明发起网络访问的方式(GET/POST)
4. 进行网络连接
5. 获得服务器响应的结果
6. 解析结果,提取需要的内容
7. 解析结果要提交到UI线程进行呈现
- HttpUrlConnection的POST请求的Demo:
URL url = new URL("http://172.60.10.117:8080/ems/regist.do");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);// 接收服务器的响应
connection.setDoOutput(true);// 要向服务器提交内容
// 在请求头中。为请求实体中的内容作说明
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
//客户端向服务器提交参数
OutputStream outputStream = connection.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
String params =
"loginname ="+user.getName()+"password="+user.getPassWord()
+"realname="+user.getRealname()+"email="+user.getEmail();
printWriter.print(params);
printWriter.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
final String result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
总结:这里面需要注意的是请求的头部文件:
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
注意设置请求方式的时候:
connection.setRequestMethod("POST");//post必须大写
2.、HttpClient的Post请求数据的Demo:
利用HttpClient的POST方式发起带参数的请求
利用POST方式发起请求,参数要放到请求实体中,并且在请求头中添加对实体中参数的说明。
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://172.60.10.117:8080/ems/login.do");
request.setHeader("Content-Type",
"application/x-www-form-urlencoded");
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("loginname",
loginUser.getName()));
parameters.add(new BasicNameValuePair("password", loginUser
.getPasswrod()));
parameters.add(new BasicNameValuePair("code", loginUser
.getCode()));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
request.setEntity(entity);
HttpResponse httpResponse = client.execute(request);
EntityUtils.toString(httpResponse.getEntity());
初学者学到的一种方式,后面返回的数据是JSON数据:希望大家多提意见。、