RT..我之前感觉Android网络通信很神奇,Magic...最近学习了网络知识,现在来总结一下怎么做
好了,就拿例子来说明原理.
说下这个Demo的用处:
1.用户可以访问一个网页
2.用户提交用户名和密码到Http服务器中,在Tomcat的控制台中显示出提交的内容.
先来介绍一下怎么访问网页
看代码
package com.hwb.service; import java.net.HttpURLConnection; import java.net.URL; import com.hwb.utils.StringReader; public class HtmlContentService { /** * 根据路径去获得数据 * @param path 访问的路径 * @return 结果 * @throws Exception */ public static byte[] getContent(String path) throws Exception { URL url = new URL(path);//构建一个URL对象 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//得到链接对象 httpURLConnection.setRequestMethod("POST");//设置请求方法 httpURLConnection.setReadTimeout(5000);///设置超时时间 if(httpURLConnection.getResponseCode()==200)//获得响应码 { byte[] arr = new byte[1024]; int res = -1; while((res = in.read(arr)) != -1) { byteArrayOutputStream.write(arr, 0,res); } byteArrayOutputStream.close(); in.close(); return byteArrayOutputStream.toByteArray(); } return null ; } }
通过这个简单的方法我们就能进行一次http请求,请求结果可以先读取成二进制数据,然后在进行相应的操作,例如,我们可以获得某个网站的源码之类的..
在应用中,我们可能会从http服务器返回一个xml文件或者是json格式的字符串,我们都可以通过这种方式获得二进制数据,然后进行相应数据的处理
好了,现在介绍下通过get,post提交数据到http服务器
首先我们需要一个http服务器,我拿Tomcat来说明,首先建立一个简单的web application.
看看这个servliet吧..
package com.hwb.control; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * * @ProjectName: [webProvider] * @Package: [com.hwb.control] * @ClassName: [UserServlet] * @Author: [hwb] * @CreateDate: [2014-6-7 下午4:15:57] * @UpdateUser: [hwb] * @UpdateDate: [2014-6-7 下午4:15:57] * @UpdateRemark: [说明本次修改内容] * @Version: [v1.0] */ public class UserServlet extends HttpServlet { /** *接受2个参数,在控制台打印出来 */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); System.out.println("name =" + name + ",password = "+ password); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
好了,我们建立一个Android应用
我建的是4.4的
现在只看关键代码
package com.hwb.service; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; public class UserService { /** * 一个简单扼方法通过get方式提交数据到http服务器上 * @param path 访问的url * @param userName 上传的用户名 * @param passWord 密码 * @return 上传成功与否 */ public static boolean sendDataByGet(String path, String userName,String passWord) { try { StringBuilder stringBuilder = new StringBuilder(path); //进行编码 stringBuilder.append("?name=").append(URLEncoder.encode(userName,"UTF-8")).append("&password=").append(URLEncoder.encode(passWord,"UTF-8")); URL url = new URL(stringBuilder.toString()); HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setConnectTimeout(5000); if(httpURLConnection.getResponseCode()==200) { return true; } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } /** * * @param path 路径 * @param userName 用户名 * @param passWord 密码 * @return 结果 */ public static boolean sendDataByPost(String path, String userName,String passWord) { try { URL url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); StringBuilder builder = new StringBuilder(); builder.append("name=").append(URLEncoder.encode(userName,"UTF-8")).append("&password=").append(URLEncoder.encode(passWord,"UTF-8")); byte[] arr = builder.toString().getBytes(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setDoOutput(true);//设置可以写数据 httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置http post请求的头部信息 请求数据内容类型 httpURLConnection.setRequestProperty("Content-Length", String.valueOf(arr.length));//设置http post请求的头部信息请求数据的长度 OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(arr);//往数据流中写数据 if(httpURLConnection.getResponseCode()==200) { return true; } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }
从中我学到了几个知识点,现在总结一下
1.首先是GET和POST请求的差别.大家都知道GET是在URL路径后面跟上参数,而POST则是放在了请求体内.我用了一个简单的工具拦截了请求,大家可以看看这个比较
那么中文怎么办呢?
请看GET
请看post
好了,从这几幅图我们知道了一些知识点和解决的办法.首先浏览器会帮我们对数据进行编码.其次,post是不是把数据放在头部的
好了现在解决编码问题,既然我们知道了浏览器会帮我们编码,那么我们为了取得数据就需要进行相应的解码.
我们先普及一下一些知识点,然后在说
我看了这篇文章,做个简单的小结.
对GET方式来说,浏览器最终是以iso8859-1的方式提交到服务器的,假设我的服务器是TOMCAT,它默认的编码方式也是ISO8859-1,如果我们直接通过request.getParameter(); 来获得数据,往往会乱码,其原因就是我们提交的时候可能先用UTF-8或者GBK的方式先进行编码..解决方法就是可以写个编码过滤器,专门为GET请求过滤.拿我的DEMO来说,我的客户端用UTF-8的方式来编码,那么我就可以这么做
new String(value.getBytes("ISO-8859-1"),"UTF-8");具体代码看下面
现在讲讲post方式,我们可以直接指定编码方式就可以获取正确的数据了
好了,看看所有的代码
package com.hwb.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.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EncodingFilter implements Filter { public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest httpServletRequest = (HttpServletRequest)arg0; HttpServletResponse httpServletResponse = (HttpServletResponse)arg1; String method = httpServletRequest.getMethod(); if(method.equals("GET")) { EncodingWrap encodingWrap = new EncodingWrap(httpServletRequest); arg2.doFilter(encodingWrap, httpServletResponse); } else if(method.equals("POST")) { httpServletRequest.setCharacterEncoding("UTF-8");//必须设置编码方式 arg2.doFilter(httpServletRequest, httpServletResponse); } } } package com.hwb.filter; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class EncodingWrap extends HttpServletRequestWrapper { public EncodingWrap(HttpServletRequest request) { super(request); } @Override public String getParameter(String name) { // TODO Auto-generated method stub if(name==null) return null; else { String value = super.getParameter(name); try { return new String(value.getBytes("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } }
好了,大致就是这样了,不正确请指出!
--------------------------------------------------------------
如果是上传文件的话,最好用socket做,因为http服务器对请求数据文件大小有限制