Android Https服务器端和客户端简单实例

AndroidHttps服务器端和客户端简单实例

工具介绍

Eclipse3.7

Tomcat 6.0.18(免安装版)

Android2.1开发环境(在Eclipse中配置好)

前提条件

JDK环境要使用我们自己安装的,笔者JDK安装目录为D:\Java\jdk1.6.0_22,在EclipseWindow-preference-installedJREs中,只选用我们自己安装的JRE,如图所示:

EclipseTomcat整合的时候,也需要选择此运行环境:

 

 

 

 

一.搭建服务器端

1.Eclipse中新建Dynamic Web Project,取名为HttpsServer

2.index.jsp内容如下:

<%@ pagelanguage="java" import="java.util.*"pageEncoding="UTF-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme() +"://"

            + request.getServerName() +":" + request.getServerPort()

            + path + "/";

%>

 

">

 

name+age JSPPage

 

 

 

      

              name: 
age:  

                     name="age" type="text"/>
     

                     type="reset" value="reset"/>

      

      

        name: 
age: 

            name="age"type="text" />
     

            type="reset"value="reset" />

   

这里其实是复用了之前Http调研的代码,我们关心的是我们手机端能不能访问该服务器端,还涉及到传递数据,具体数据显示在TestService表示。

3.TestService代码如下:

package com.veer;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

import javax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

public class TestServiceextends HttpServlet {

 

  

    private static final long serialVersionUID= 1L;

 

    protected void doGet(HttpServletRequestreq, HttpServletResponse resp)

            throws ServletException,IOException {

        String name =req.getParameter("name");

        String age =req.getParameter("age");

 

        resp.setContentType("text/html");

 

        PrintWriter out = resp.getWriter();

 

       out.println("name&age

 

        out.println("name:" + name + "
");

 

        out.println("age:" + age +"
");

 

        System.out.println("name=" +name);

        System.out.println("age=" +age);

        out.flush();

    }

 

    protected void doPost(HttpServletRequestreq, HttpServletResponse resp)

            throws ServletException,IOException {

        req.setCharacterEncoding("utf-8");

        String name =req.getParameter("name");

        String age =req.getParameter("age");

 

       resp.setContentType("text/html");

       resp.setCharacterEncoding("utf-8"); // 设置返回给客户端的文本格式,可解决文字编码不统一的问题

        PrintWriter out = resp.getWriter();

 

       out.println("name&age

 

        out.println("name:" + name + "
");

 

        out.println("age:" + age +"
");

        System.out.println("name=" +name);

        System.out.println("age=" +age);

        out.flush();

    }

 

}

 

4.修改web.xml文件,在倒数第二行加入:

    This is the descriptionof my J2EE component

    This is the displayname of my J2EE component

   TestService

    com.veer.TestService

 

   TestService

   /TestService

 

 

至此,未加密钥的服务器端就已经搭建好。

二.配置密钥

2.1 D盘建立文件夹cer,再在里面建立文件夹tomcat

2.2 进入cmd,依次键入cd\d:cd cercd tomcat,进入到D:\cer\tomcat目录下面;

2.3 生成服务器端密钥

键入D:\cer\tomcat>

keytool -genkey -aliastomcat -keyalg RSA -keystore server.keystore -validity 36000

解释:keytooljdk下的命令行工具。

alias 随意指定,表示别名。keyalg表示加密算法为RSA,输出文件为server.keystore

这里面需要输入密码(我们输入123456),另外注意“您的名字与姓氏是什么?”,这一项要输入tomcat所在主机的IP或域名,客户端访问tomcat时会涉及到这个地址,笔者局域网的IP192.168.1.213,所以我们输入该IP

此时在D:\cer\tomcat里面就会生成一个server.keystore文件,不要关闭cmd,还有操作要进行;

 

2.4 server.keystore生成server.cer

键入:D:\cer\tomcat>

keytool -export -aliastomcat -file server.cer -keystore server.keystore -storepass 123456

此时在D:\cer\tomcat里面就会生成一个server.cer文件。解释:这个是浏览器可以识别的证书,用于导入浏览器。

不要关闭cmd,还有操作要进行。

2.5 这个时候tomcat就可以启动ssl了,以tomcat6.0为例,在server.xml中拷入(或是更改)如下片段:

="true"acceptCount="100" clientAuth="false" disableUploadTimeout="true"enableLookups="true"keystoreFile="D:/cer/tomcat/server.keystore"keystorePass="123456" maxSpareThreads="75"maxThreads="200" minSpareThreads="5" port="8443"protocol="org.apache.coyote.http11.Http11NioProtocol"scheme="https" secure="true"sslProtocol="TLS"/>

其中clientAuth="false",表示单向验证,为true的话则是双向认证。

 

这时启动tomcat,打开IE,输入https://192.168.1.213:8443/会提示没有证书,但能点进去。

我们可以双击刚才生成的server.cer,把它导入“受信任的根证书颁发机构”,就能看到浏览器上的小锁了。

 

三.特别说明

我们需要下载bcprov-jdk15-135.jarsunjce_provider.jar(可能已经存在),放入D:\Java\jdk1.6.0_22\jre\lib\ext下面。同时要修改D:\Java\jdk1.6.0_22\j\jre\lib\security\java.security文件,

找到security.provider.1=sun.security.provider.Sun这行,这里有好几行,在最后一行加上security.provider.10=org.bouncycastle.jce.provider.BouncyCastleProvider,笔者本来有9号,所以新一行的序号为10

 

cmd中继续键入:D:\cer\tomcat>

keytool -import -aliastomcat -file server.cer -keystore server_trust.keystore -storepass 123456-storetype BKS -providername "BC"

这时候在D:\cer\tomcat里面就会生成一个server_trust.keystore文件。

解释:将在客户端用到这个信任的密钥。

 

 

四.搭建客户端

按照正常的步骤,我们建立一个Android Project,需要注意的是新建立一个文件夹res/raw,将server_trust.keystore拷贝至其中,在AndroidMainfest.xml中加入。如下图所示:

HttpsClientActivity 代码如下:

 

package com.veer;

 

importjava.io.InputStream;

importjava.security.KeyStore;

 

importorg.apache.http.HttpEntity;

importorg.apache.http.HttpResponse;

importorg.apache.http.client.HttpClient;

importorg.apache.http.client.methods.HttpGet;

importorg.apache.http.client.methods.HttpUriRequest;

importorg.apache.http.conn.scheme.Scheme;

importorg.apache.http.conn.ssl.SSLSocketFactory;

importorg.apache.http.impl.client.DefaultHttpClient;

 

importandroid.app.Activity;

import android.os.Bundle;

import android.view.View;

importandroid.view.View.OnClickListener;

importandroid.widget.Button;

 

public classHttpsClientActivity extends Activity {

    /** Called when the activity is firstcreated. */

 

    private Button testButton;

    private String httpsUrl ="https://192.168.1.213:8443/HttpsServer/TestService";

    HttpClient hc = new DefaultHttpClient();

 

    @Override

    public void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

 

        testButton = (Button)findViewById(R.id.testButton);

        testButton.setOnClickListener(newOnClickListener() {

 

            @Override

            public void onClick(View v) {

                try {

                    initKey();

                } catch (Exception e) {

                    e.printStackTrace();

                }

 

                try {

                    String result = getData(httpsUrl);

                   System.out.println("result=" + result);

                } catch (Exception e) {

                    e.printStackTrace();

                }

 

            }

        });

    }

 

    private void initKey() throws Exception {

        KeyStore trustStore =KeyStore.getInstance("BKS");

        trustStore.load(

               getBaseContext().getResources().openRawResource(

                        R.raw.server_trust),"123456".toCharArray());

        SSLSocketFactory socketFactory = newSSLSocketFactory(trustStore);

        Scheme sch = newScheme("https", socketFactory, 8443);

       hc.getConnectionManager().getSchemeRegistry().register(sch);

 

    }

 

    private String getData(String url) throwsException {

        HttpUriRequest hr = new HttpGet(url);

        HttpResponse hres = hc.execute(hr);

        HttpEntity he = hres.getEntity();

        InputStream is = he.getContent();

        StringBuffer sb = new StringBuffer();

        byte[] bytes = new byte[1024];

        for (int len = 0; (len =is.read(bytes)) != -1;) {

            sb.append(new String(bytes, 0, len,"utf-8"));

        }

        return sb.toString();

    }

}

 

 

 

main.xml代码如下:

   android:layout_width="fill_parent"

   android:layout_height="fill_parent"

    android:orientation="vertical">

 

   

        android:id="@+id/testButton"

       android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="HTTPS Test"/>

 

 

将该Android项目运行起来,点击按钮,在logcat中就可以看到打印信息:

console控制台中可以看到信息:

至迟,手机端对https服务器简单的访问已经完成,至于其他的具体功能还要靠大家自己去扩展和封装。

你可能感兴趣的:(Android)