搭建本地server,响应Android客户端HTTP请求

来源:互联网 发布:富士康mac是什么意思啊 编辑:程序博客网 时间:2024/05/18 14:46

有些时候,我们可能需要自己搭建本地服务器,来测试某个客户端功能(公共API不满足自己需要的情况下),如果自己写接口,写在servlet中方便点。本文以普通的get,post请求为例,分享下如何搭建本地Server(Tomcat+servlet),测试网络请求,并演示HttpURLConnection的使用。

一,安装Eclipse for JavaEE

官方下载:http://www.eclipse.org/downloads/
直接傻瓜安装,另外自行安装jdk,tomcat。

二,创建server项目

1,运行Eclipse,File->Dynamic Web project

Create a standalone Dynamic Web project or add it to a new or existing Enterprise Application.

2,新建servlet,配置web.xml

新建LoginServlet,如果报错,自行导入servlet库(项目属性->Build Path->add Libraries),安装了tomact也有这个。
查看配置文件,位于项目根目录WEB-INF/web.xml,确保有url映射。

  <servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/servlet/LoginServlet</url-pattern>  </servlet-mapping>

3,写服务端代码,根据参数返回json

public class LoginServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("UTF-8");        response.setContentType("text/html;charset=UTF-8");        PrintWriter out = response.getWriter();        String username = request.getParameter("username");        if(username!=null&&!"".equals(username)){            String result = "\""+username+"\"";            out.write("{\"username\":"+result+"}");            return;        }    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {            doGet(request, response);    }}

如果写在jsp里面,可以这样:

<body>  <!--    欢迎您!测试JSP,duqian    -->    <%    String name=request.getParameter("username");    String age=request.getParameter("age");    out.println("用户名="+name+",年龄="+age);    %>  </body>

三,创建android项目

使用android stduio 创建简单的工程。访问上面创建的servlet,如果是真机,需要改localhost为pc的IP地址。
别忘了权限:

 <uses-permission  android:name="android.permission.INTERNET"/>

我使用HttpURLConnection演示请求的过程,不建议使用httpClinet,android 6.0已经废弃它了,要使用必需添加依赖:

useLibrary 'org.apache.http.legacy'//android 6.0(api23) 后,不再提供org.apache.http.*(只保留几个类).

如果是请求一个jsp页面,将返回整个页面的源代码。以上servlet仅仅out.write一个字符串,所以客户端接受到的只有json字符串。代码如下:

 public static void testHttpURLConnection() {        // 1.获取请求的路径:改成你自己的        //final String path ="http://192.168.10.245:8080/Android/index.jsp?username=duqian&age=25";//get        final String path ="http://192.168.100.47:8080/Android/servlet/LoginServlet";//post        HttpURLConnection conn = null;        InputStream is = null;        try {            // 2.获取url对象            URL url = new URL(path);            // 3.得到连接的对象            conn = (HttpURLConnection) url.openConnection();            // 4.设置连接的参数            // 设置请求方式            //conn.setRequestMethod("GET");            conn.setRequestMethod("POST");            // 设置连接超时时间            conn.setConnectTimeout(5000);            // 设置读取数据的超时时间            conn.setReadTimeout(5000);            conn.setUseCaches(false);// Post 请求不能使用缓存            // 设置允许读取服务器端返回的数据            conn.setDoInput(true);            // 5.连接服务器            //conn.connect();//如果是post请求,不要加这个,否则可能IllegalStateException: Already connected            //如果是get请求,参数写url中,就不需要post参数            conn.setDoOutput(true);//4.0中设置httpCon.setDoOutput(true),将导致请求以post方式提交            final OutputStream outputStream = conn.getOutputStream();            outputStream.flush();            outputStream.write("username=dusan".getBytes("UTF-8"));            outputStream.close();            // 6.获取返回的服务器端的响应码。            int responseCode = conn.getResponseCode();            // 7.只有响应码是200时,方可正常读取            if (200==responseCode) {                is = conn.getInputStream();                // 将获取的输入流中的数据转换为字符串                final String content=StreamTools.readStream(is);                   LogUtils.debug(TAG,"content="+content);            }else{                LogUtils.debug(TAG,"responseCode="+responseCode);            }        }catch (Exception e){            LogUtils.debug(TAG,e.toString());        }    }

将接受到的字节流转化成字符串,UTF-8编码格式。

public static String readStream(InputStream in) throws Exception{         ByteArrayOutputStream baos = new ByteArrayOutputStream();          int len = -1;         byte buffer[] = new byte[1024];         while((len=in.read(buffer))!=-1){             baos.write(buffer, 0, len);         }         in.close();        return new String(baos.toByteArray(),"UTF-8");        //return new String(baos.toByteArray());    }

以上代码,get和post请求写在了一起,并且jsp和servet页面都有测试。如果是get请求,就把参数写在url地址上面,否则以流的形式向服务端发送。
servlet返回的形式,通常的接口都以json格式返回result,方便解析处理。如:

{"name":"duqian-291902259"}

四,总结

如果自己写接口,写在servlet中方便点,如果写在jsp返回的是全面页面内容。多个参数也一样处理。
杜乾,Dusan,Q 291902259,欢迎交流。

0 0
原创粉丝点击