1、.页眉.页脚由于刚接触 android 开发,故此想把学到的基础知识记录一下,以备查询,故此写的比较啰嗦:步骤如下:一、介绍:此文主要是介利用 android 网络通信功能把 android 客户端的数据传给web 服务端进行操作此项目列举三个个传值方式:1、GET 方式,2、POST 方式,3、HttpClient 方式二、新建一个 android 工程NewsManage工程目录:三、AndroidManifest.xml 配置清单由于要访问网络,故需要添加网络访问权限,红色标注添加部分.页眉.页脚四、main.xml 配置:.页眉.页脚五、string.xml 配置:Hello Worl
2、d, NewsManageActivity!资讯管理视频标题播放时长保存保存成功保存失败六、NewsManageActivity.java Activity 源码:package com.example.newsmanage;import com.example.service.NewsService;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import and
3、roid.widget.Toast;public class NewsManageActivity extends Activity /* Called when the activity is first created. */EditText titleText;EditText lengthText;Button button;Overridepublic void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState);setContentView(R.layout.main);titleText =
4、 (EditText) this.findViewById(R.id.title);.页眉.页脚lengthText = (EditText) this.findViewById(R.id.timelength);button = (Button) this.findViewById(R.id.button);public void save(View v) throws ExceptionString title = titleText.getText().toString();String timelength = lengthText.getText().toString();boole
5、an result = NewsService.save(title,timelength);if(result)Toast.makeText(getApplicationContext(),R.string.success, Toast.LENGTH_LONG).show(); else Toast.makeText(getApplicationContext(),R.string.fail, Toast.LENGTH_LONG).show(); 七、NewsService .java 业务类源码:注:业务类提供三种发送请求的方式:get/post/httpClientpackage com
6、.example.service;import java.io.OutputStream;import .HttpURLConnection;import .URL;import .URLEncoder;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.
7、entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;public class NewsService /*.页眉.页脚* 保存数据,传递参数给 web 服务器端* param title 标题* param timelength 时长* return*/public static boolean
8、 save(String title, String timelength) throws Exception /119.119.228.105为本机 IP 地址,不能用 localhost 代替String path = “http:/119.119.228.105:8080/web/ManageServlet“;Map params = new HashMap();params.put(“title“, title);params.put(“timelength“, timelength);/get 请求方式/return sendGETRequest(path,params,“UTF-8
9、“);/post 请求方式/return sendPOSTRequest(path,params,“UTF-8“);/httpClient 请求方式,如果单纯传递参数的话建议使用 GET 或者 POST 请求方式return sendHttpClientPOSTRequest(path,params,“UTF-8“);/httpclient已经集成在 android 中/* 通过 HttpClient 发送 post 请求* param path* param params* param encoding* return* throws Exception*/private static bo
10、olean sendHttpClientPOSTRequest(String path,Map params, String encoding) throws Exception List pairs = new ArrayList();/存放请求参数for(Map.Entry entry:params.entrySet()pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue();/防止客户端传递过去的参数发生乱码,需要对此重新编码成 UTF-8UrlEncodedFormEntity entity = new UrlE
11、ncodedFormEntity(pairs,encoding);HttpPost httpPost = new HttpPost(path);httpPost.setEntity(entity);.页眉.页脚DefaultHttpClient client = new DefaultHttpClient();HttpResponse response = client.execute(httpPost);if(response.getStatusLine().getStatusCode() = 200)return true;return false;/* 发送 post 请求* param
12、 path 请求路径* param params 请求参数* param encoding 编码* return 请求是否成功*/private static boolean sendPOSTRequest(String path,Map params, String encoding) throws ExceptionStringBuilder data = new StringBuilder(path);for(Map.Entry entry:params.entrySet()data.append(entry.getKey().append(“=“);/防止客户端传递过去的参数发生乱码,
13、需要对此重新编码成 UTF-8data.append(URLEncoder.encode(entry.getValue(),encoding);data.append(“data.deleteCharAt(data.length() - 1);byte entity = data.toString().getBytes();/得到实体数据HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod(“PO
14、ST“);conn.setDoOutput(true);/设置为允许对外输出数据conn.setRequestProperty(“Content-Type“, “application/x-www-form-urlencoded“);conn.setRequestProperty(“Content-Length“, String.valueOf(entity.length);OutputStream outStream = conn.getOutputStream();outStream.write(entity);/写到缓存.页眉.页脚if(conn.getResponseCode()=20
15、0)/只有取得服务器返回的 http 协议的任何一个属性时才能把请求发送出去return true;return false;/* 发送 GET 请求* param path 请求路径* param params 请求参数* return 请求是否成功* throws Exception*/private static boolean sendGETRequest(String path,Map params,String encoding) throws Exception StringBuilder url = new StringBuilder(path);url.append(“?“)
16、;for(Map.Entry entry:params.entrySet()url.append(entry.getKey().append(“=“);/get 方式请求参数时对参数进行 utf-8编码,URLEncoder/防止客户端传递过去的参数发生乱码,需要对此重新编码成 UTF-8url.append(URLEncoder.encode(entry.getValue(), encoding);url.append(“url.deleteCharAt(url.length()-1);HttpURLConnection conn = (HttpURLConnection) new URL(
17、url.toString().openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod(“GET“);if(conn.getResponseCode() = 200)return true;return false;八、由于要把数据传递给 web 服务端,而 web 端传递过来的数据有两种格式,故需要新建一个 web 服务,使之能接收 android 客户端传递的参数;1、新建一个 servlet 可以接收传递的参数,源码如下:.页眉.页脚package com.example.servlet;import java
18、.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/* Servlet implementation class ManageServlet*/public class ManageServlet extends HttpServlet private static final lo
19、ng serialVersionUID = 1L;/* see HttpServlet#HttpServlet()*/public ManageServlet() super();/* see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException String tit
20、le = request.getParameter(“title“);/把客户端传递过来的参数进行重新编码使之能支持中文/title = new String(title.getBytes(“ISO8859-1“),“UTF-8“);/使用过滤器后就不需要每次都要进行此操作String timelength = request.getParameter(“timelength“);System.out.println(“视频名称:“+title);System.out.println(“播放时长:“+timelength);/* see HttpServlet#doPost(HttpServl
21、etRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException String title = request.getParameter(“title“);/把客户端传递过来的参数进行重新编码使之能支持中文/title = new String(title.getBytes(“ISO8859-1“),“UTF-8“);/使用过.页
22、眉.页脚滤器后就不需要每次都要进行此操作String timelength = request.getParameter(“timelength“);System.out.println(“视频名称:“+title);System.out.println(“播放时长:“+timelength);2、由于传递过来的参数默认编码为 ISO8895-1,故打印后台的参数回事乱码故需要传递的过来的参数进行编码,但是如果每次都要对传递过来的参数都要 进行编码转换,是比较麻烦的,故需要建立一个拦截器,对传递过来的参数进行统一在一起进行编码转换,当请求/*时拦截器先进行编码处理:拦截器代码如下:Encodi
23、ngFilter .java 源码如下:package com.example.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet
24、.http.HttpServletRequest;/* Servlet Filter implementation class EncodingFilter*/public class EncodingFilter implements Filter /* Default constructor.*/public EncodingFilter() /* see Filter#destroy()*/public void destroy() .页眉.页脚/* see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)*/pu
25、blic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException HttpServletRequest req = (HttpServletRequest) request;if(“GET“.equals(req.getMethod()EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(req);chain.doFilter(wr
26、apper, response); else /postreq.setCharacterEncoding(“UTF-8“);chain.doFilter(request, response);/* see Filter#init(FilterConfig)*/public void init(FilterConfig fConfig) throws ServletException EncodingHttpServletRequest .java 源码如下:package com.example.filter;import java.io.UnsupportedEncodingExceptio
27、n;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;public class EncodingHttpServletRequest extends HttpServletRequestWrapper private HttpServletRequest request;public EncodingHttpServletRequest(HttpServletRequest request) super(request);.页眉.页脚this.requ
28、est = request;Overridepublic String getParameter(String name) String value = request.getParameter(name);if(value!=null)try value = new String(value.getBytes(“ISO8859-1“),“UTF-8“); catch (UnsupportedEncodingException e) e.printStackTrace();return value;注意:在运行 android 项目前必须先运行 web 服务九、先运行 web 服务器,然后运行
29、 android 项目,发送参数后,web 后台就可以打印出相应的信息十、注意事项以及相关知识点:1、由于涉及访问网络,故需要添加网络访问权限2、访问 web 服务时地址必须写网络的 IP 地址,否则会在本地服务上查找3、熟悉怎么向 web 服务端发送请求以及方式(http 协议)GET 方式:HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod(“GET“);conn.getResponseCod
30、e() = 200 来判断是否请求成功.页眉.页脚POST 方式:byte entity = data.toString().getBytes();/得到实体数据HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod(“POST“);conn.setDoOutput(true);/设置为允许对外输出数据conn.setRequestProperty(“Content-Type“, “applicat
31、ion/x-www-form-urlencoded“);conn.setRequestProperty(“Content-Length“, String.valueOf(entity.length);OutputStream outStream = conn.getOutputStream();outStream.write(entity);/写到缓存if(conn.getResponseCode()=200)/只有取得服务器返回的 http 协议的任何一个属性时才能把请求发送出去return true;HttpClient 方式:List pairs = new ArrayList();/存
32、放请求参数for(Map.Entry entry:params.entrySet()pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue();/防止客户端传递过去的参数发生乱码,需要对此重新编码成 UTF-8UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,encoding);HttpPost httpPost = new HttpPost(path);httpPost.setEntity(entity);DefaultHttpClient clie
33、nt = new DefaultHttpClient();HttpResponse response = client.execute(httpPost);.页眉.页脚if(response.getStatusLine().getStatusCode() = 200)return true;4、乱码产生的原因:(1) 、 通过 get 方式提交请求参数时,没有对中文进行 URL 编码(2) 、 Tomcat 服务器默认采用 ISO8895-1编码得到的参数如果乱码表示为 ,则说明是由于客户端传递参数没有编码的原因如果乱码表示为?,则说明是由于服务器端的默认编码不一致或者不支持中文的原因5、熟悉拦截器的使用以及原理