安卓中进行基于HTTP协议的网络访问
两种方式:
HttpClient (apache开发)
HttpURLConnection(google在发布安卓时在Java基础上修改得到的)
进行网络访问的基本步骤:
1. 创建HC/UC对象
2. 声明发起网络访问的方式(GET/POST)
3. 进行网络连接
4. 获得服务器响应的结果
5. 解析结果,提取需要的内容
6. 解析结果要提交到UI线程进行呈现
Ps:必须申请权限 INTERNET访问权限;任何网络访问的相关代码,必须在工作线程中执行!
一、HttpClient (apache开发)方式:
1. post提交方式
HttpClient client = new DefaultHttpClient();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://172.88.134.152:8080/ems/login.do");
//添加一个请求头,对请求实体中的参数做一个说明
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setHeader("Cookie", sid);
//在post中添加请求参数,请求参数会添加在请求实体中
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("loginname", loginUser.getUserName()));
parameters.add(new BasicNameValuePair("password", loginUser.getPassword()));
parameters.add(new BasicNameValuePair("code", loginUser.getCode()));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity respEntity = response.getEntity();
String line = EntityUtils.toString(respEntity);
2. get提交
//创建HC对象
URL url = new URL("http://172.88.134.152:8080/ems/getCode.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//声明获取方式 GET | POST
connection.setRequestMethod("GET");
connection.setDoInput(true);
//发起网络访问,获得服务器响应
connection.connect();
//解析响应的结果
InputStream is = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
//将解析结果从工作线程提交到主线程
Message.obtain(handler, 101, bitmap).sendToTarget();
二、HttpURLConnection(google在发布安卓时在Java基础上修改得到的)方式:
URL url = new URL("http://172.88.134.152:8080/ems/login.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");//提交方式:GET | POST
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Cookie", sid);
connection.connect();
//客户端提交数据
OutputStream out = connection.getOutputStream();
PrintWriter writer = new PrintWriter(out, true);
writer.print(getParams(loginUser));
writer.close();
//解析服务器响
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();