android http练习-android+servlet+mysql

7 篇文章 0 订阅
4 篇文章 0 订阅

    项目中手机客户端要播放远程服务器的图片和视频,还要获取解密的密钥。所以做了一个demo

    服务器端用的是Myeclipse+Tomcat+servlet+MySQL,密钥传输用的是json,用的是http协议。网络环境是手机和服务器(笔记本)都连接同一个无线路由器

一、服务器

     1、在Myeclipse里配置Tomcat,百度一下就行,很简单。

     2、新建一个web工程,如下,存了5张图片,一个视频和一个xml文本

    3、在数据库中建立一张表,存放密钥

    4、服务器端,数据库服务类

  1. package com.json.service;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.ResultSet;  
  6. import java.sql.Statement;  
  7. import com.json.domain.Skey;  
  8.   
  9. public class JsonService {  
  10.   
  11.     public JsonService() {  
  12.         // TODO Auto-generated constructor stub  
  13.     }  
  14.           
  15.     public Skey getSkey(){  
  16.         String name=”“;  
  17.         String skey=”“;  
  18.     // 驱动程序名  
  19.         String driver = ”com.mysql.jdbc.Driver”;  
  20.         // URL指向要访问的数据库名scutcs  
  21.         String url = ”jdbc:mysql://127.0.0.1:3306/json”;  
  22.         // MySQL配置时的用户名  
  23.         String user = ”root”;   
  24.         // MySQL配置时的密码  
  25.         String password = ”*****”;  
  26.         try {   
  27.          // 加载驱动程序  
  28.          Class.forName(driver);  
  29.          // 连续数据库  
  30.          Connection conn = DriverManager.getConnection(url, user, password);  
  31.          if(!conn.isClosed())   
  32.           System.out.println(”Succeeded connecting to the Database!”);  
  33.          // statement用来执行SQL语句  
  34.          Statement statement = conn.createStatement();  
  35.          // 要执行的SQL语句  
  36.          String sql = ”select * from skey”;  
  37.          // 结果集  
  38.          ResultSet rs = statement.executeQuery(sql);  
  39.   
  40.          System.out.println(”—————–”);  
  41.          System.out.println(”执行结果如下所示:”);  
  42.          System.out.println(”—————–”);  
  43.          while(rs.next()) {  
  44.           name = rs.getString(”name”);  
  45.           skey= rs.getString(”skey”);  
  46.          }  
  47.          rs.close();  
  48.          conn.close();  
  49.   
  50.         } catch(Exception e) {  
  51.   
  52.         System.out.println(”Sorry,can`t find the Driver!”);   
  53.          e.printStackTrace();  
  54.         }   
  55.         System.out.println(”name:”+name);  
  56.         System.out.println(”skey:”+skey);  
  57.           
  58.         Skey skey_video=new Skey(name,skey);  
  59.         return skey_video;  
  60.     }  
  61.       
  62. }  
  63.     5、servlet类,响应客户端请求,把数据封装成json发送  
  64. <pre name=”code” class=“java”>package com.json.action;  
  65.   
  66. import java.io.IOException;  
  67. import java.io.PrintWriter;  
  68. import javax.servlet.ServletException;  
  69. import javax.servlet.http.HttpServlet;  
  70. import javax.servlet.http.HttpServletRequest;  
  71. import javax.servlet.http.HttpServletResponse;  
  72. import com.json.service.JsonService;  
  73. import com.json.tools.JsonTools;  
  74.   
  75. public class JsonAction extends HttpServlet {  
  76.   
  77.     private JsonService service;  
  78.     /** 
  79.      * Constructor of the object. 
  80.      */  
  81.     public JsonAction() {  
  82.         super();  
  83.     }  
  84.   
  85.     /** 
  86.      * Destruction of the servlet. <br> 
  87.      */  
  88.     public void destroy() {  
  89.         super.destroy(); // Just puts “destroy” string in log  
  90.         // Put your code here  
  91.     }  
  92.   
  93.     /** 
  94.      * The doGet method of the servlet. <br> 
  95.      * 
  96.      * This method is called when a form has its tag value method equals to get. 
  97.      *  
  98.      * @param request the request send by the client to the server 
  99.      * @param response the response send by the server to the client 
  100.      * @throws ServletException if an error occurred 
  101.      * @throws IOException if an error occurred 
  102.      */  
  103.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  104.             throws ServletException, IOException {  
  105.   
  106.         response.setContentType(”textml;charsset=utf-8”);  
  107.         request.setCharacterEncoding(”utf-8”);  
  108.         response.setCharacterEncoding(”utf-8”);  
  109.         PrintWriter out = response.getWriter();  
  110.         String jsonString=null;  
  111.         String action_flag=request.getParameter(”action_flag”);  
  112.     if(action_flag.equals(“skey”)){  
  113.             jsonString=JsonTools.createJsonString(”skey”, service.getSkey());  
  114.         }  
  115.         out.println(jsonString);  
  116.         out.flush();  
  117.         out.close();  
  118.     }  
  119.           
  120.   
  121.     /** 
  122.      * The doPost method of the servlet. <br> 
  123.      * 
  124.      * This method is called when a form has its tag value method equals to post. 
  125.      *  
  126.      * @param request the request send by the client to the server 
  127.      * @param response the response send by the server to the client 
  128.      * @throws ServletException if an error occurred 
  129.      * @throws IOException if an error occurred 
  130.      */  
  131.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  132.             throws ServletException, IOException {  
  133.   
  134.         this.doGet(request, response);  
  135.     }  
  136.   
  137.     /** 
  138.      * Initialization of the servlet. <br> 
  139.      * 
  140.      * @throws ServletException if an error occurs 
  141.      */  
  142.     public void init() throws ServletException {  
  143.         // Put your code here  
  144.         service=new JsonService();  
  145.     }  
  146.   
  147. }  
  148.     6、下面是两个工具类,一个存数据,一个封装成json数据  
  149. <pre name=”code” class=“java”>package com.json.domain;  
  150.   
  151. public class Skey {  
  152.   
  153.     private String name;  
  154.     private String skey;  
  155.     public Skey(String name, String skey) {  
  156.         super();  
  157.         this.name = name;  
  158.         this.skey = skey;  
  159.     }  
  160.     public String getName() {  
  161.         return name;  
  162.     }  
  163.     public void setName(String name) {  
  164.         this.name = name;  
  165.     }  
  166.     public String getSkey() {  
  167.         return skey;  
  168.     }  
  169.     public void setSkey(String skey) {  
  170.         this.skey = skey;  
  171.     }  
  172.     @Override  
  173.     public String toString() {  
  174.         return “Skey [name=” + name + “, skey=” + skey + “]”;  
  175.     }  
  176.       
  177. }  
  178.   
  179. <pre name=”code” class=“java”>package com.json.tools;  
  180.   
  181. import net.sf.json.JSONObject;  
  182.   
  183. public class JsonTools {  
  184.     
  185.     public JsonTools(){  
  186.           
  187.     }  
  188.     public static String createJsonString(String key,Object value){  
  189.           
  190.         JSONObject jsonObject=new JSONObject();  
  191.         jsonObject.put(key, value);  
  192.         return jsonObject.toString();  
  193.     }  
  194. }  
package com.json.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.json.domain.Skey;

public class JsonService {

    public JsonService() {
        // TODO Auto-generated constructor stub
    }

    public Skey getSkey(){
        String name="";
        String skey="";
    // 驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名scutcs
        String url = "jdbc:mysql://127.0.0.1:3306/json";
        // MySQL配置时的用户名
        String user = "root"; 
        // MySQL配置时的密码
        String password = "*****";
        try { 
         // 加载驱动程序
         Class.forName(driver);
         // 连续数据库
         Connection conn = DriverManager.getConnection(url, user, password);
         if(!conn.isClosed()) 
          System.out.println("Succeeded connecting to the Database!");
         // statement用来执行SQL语句
         Statement statement = conn.createStatement();
         // 要执行的SQL语句
         String sql = "select * from skey";
         // 结果集
         ResultSet rs = statement.executeQuery(sql);

         System.out.println("-----------------");
         System.out.println("执行结果如下所示:");
         System.out.println("-----------------");
         while(rs.next()) {
          name = rs.getString("name");
          skey= rs.getString("skey");
         }
         rs.close();
         conn.close();

        } catch(Exception e) {

        System.out.println("Sorry,can`t find the Driver!"); 
         e.printStackTrace();
        } 
        System.out.println("name:"+name);
        System.out.println("skey:"+skey);

        Skey skey_video=new Skey(name,skey);
        return skey_video;
    }

}
    5、servlet类,响应客户端请求,把数据封装成json发送
<pre name="code" class="java">package com.json.action;

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;
import com.json.service.JsonService;
import com.json.tools.JsonTools;

public class JsonAction extends HttpServlet {

    private JsonService service;
    /**
     * Constructor of the object.
     */
    public JsonAction() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("textml;charsset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String jsonString=null;
        String action_flag=request.getParameter("action_flag");
    if(action_flag.equals("skey")){
            jsonString=JsonTools.createJsonString("skey", service.getSkey());
        }
        out.println(jsonString);
        out.flush();
        out.close();
    }


    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doGet(request, response);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
        service=new JsonService();
    }

}
    6、下面是两个工具类,一个存数据,一个封装成json数据
<pre name="code" class="java">package com.json.domain;

public class Skey {

    private String name;
    private String skey;
    public Skey(String name, String skey) {
        super();
        this.name = name;
        this.skey = skey;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSkey() {
        return skey;
    }
    public void setSkey(String skey) {
        this.skey = skey;
    }
    @Override
    public String toString() {
        return "Skey [name=" + name + ", skey=" + skey + "]";
    }

}

<pre name="code" class="java">package com.json.tools;

import net.sf.json.JSONObject;

public class JsonTools {

    public JsonTools(){

    }
    public static String createJsonString(String key,Object value){

        JSONObject jsonObject=new JSONObject();
        jsonObject.put(key, value);
        return jsonObject.toString();
    }
}
7、发布到tomcat上就可以

 
  
 
8、然后看一下IP地址 控制台输入ipconfig

9、查看jsonroject 的url映射
  1. <servlet-mapping>  
  2.     <servlet-name>JsonAction<rvlet-name>  
  3.     <url-pattern>/servlet/JsonAction</url-pattern>  
  4. <servlet-mapping>   
  5.     10、tomcat的端口是8080,所以最后的地址就是  
  6.     skey请求地址:http://192.168.1.114:8080/jsonProject/servlet/jsonAction?action_flag=skey  
  7.     图片地址:http://192.168.1.114:8080/jsonProject/a.jpg  
  8.     视频地址:http://192.168.1.114:8080/jsonProject/tudou-skey.mp4  
  9. 二、客户端  
  10.     1、json数据解析类  
  11. <pre name=“code” class=“java”>package com.and.netease.json;  
  12.   
  13. import java.io.ByteArrayOutputStream;  
  14. import java.io.InputStream;  
  15. import java.net.HttpURLConnection;  
  16. import java.net.URL;  
  17. import java.util.ArrayList;  
  18. import java.util.List;  
  19. import org.json.JSONObject;  
  20. import org.json.JSONArray;  
  21. import com.and.netease.domain.Skey;  
  22. import android.R.integer;  
  23.   
  24.   
  25. public class JsonParse {  
  26.       
  27.     public static Skey getListPerson(String urlPath) throws Exception{  
  28.         Skey skey_video=new Skey();  
  29.         byte[] data=readParse(urlPath);  
  30.         String jsonString=new String(new String(data));   
  31.         JSONObject jsonObject=new JSONObject(jsonString);  
  32.         JSONObject personObject=jsonObject.getJSONObject(“skey”);  
  33.         skey_video.setName(personObject.getString(“name”));  
  34.         skey_video.setSkey(personObject.getString(“skey”));  
  35.           
  36.         return skey_video;    
  37.     }  
  38.   
  39.     private static byte[] readParse(String urlPath) throws Exception{  
  40.         // TODO Auto-generated method stub  
  41.         ByteArrayOutputStream outStream=new ByteArrayOutputStream();  
  42.         byte[] data=new byte[1024];  
  43.         int len=0;  
  44.         URL url=new URL(urlPath);  
  45.         HttpURLConnection conn=(HttpURLConnection)url.openConnection();  
  46.         conn.setConnectTimeout(3000);  
  47.         conn.setDoInput(true);  
  48.         conn.setRequestMethod(“GET”);  
  49.         conn.connect();  
  50.         int responseCode=conn.getResponseCode();  
  51.         if(responseCode==200){  
  52.         InputStream inStream=conn.getInputStream();  
  53.           
  54.         while ((len=inStream.read(data))!=-1) {  
  55.             outStream.write(data, 0, len);  
  56.         }  
  57.         inStream.close();  
  58.         return outStream.toByteArray();  
  59.         }  
  60.         return null;  
  61.     }  
  62.   
  63. }  
  64.     2、加密图片的解密和接收,就是把上一篇文章的本地demo移植过来   
  65. <pre name=“code” class=“java”>public class ImageAdapter {  
  66.         static int flag=1;  
  67.     public static Bitmap readBitmap(String url,String fileName) {  
  68.       
  69.             String savePath=“/mnt/sdcard/UCDownloads/”;//手机本地存储路径  
  70.             String srcPath=savePath+fileName;  
  71.             FileUtils fileUtils =new FileUtils();  
  72.             try {  
  73.                 InputStream inputStream=getInputStream(url);  
  74.                 File file=fileUtils.write2SDFromInput(“UCDownloads/”, fileName, inputStream);//把图片以文件形式下载到手机  
  75.                 flag=MyAESAlgorithm.fileDecrypt(srcPath, Constant.Skey, srcPath,1); //解密  
  76.                   
  77.             } catch (Exception e) {  
  78.                 // TODO: handle exception  
  79.             }  
  80.             return readFile(srcPath);  
  81.     }  
  82.   
  83.   
  84.     public static InputStream getInputStream(String URL_PATH) {  
  85.         InputStream inputStream = null;  
  86.         HttpURLConnection httpURLConnection = null;  
  87.         try {  
  88.             URL url = new URL(URL_PATH);  
  89.             if (url != null) {  
  90.                 httpURLConnection = (HttpURLConnection) url.openConnection();  
  91.                 // 设置网络超时时间  
  92.                 httpURLConnection.setConnectTimeout(3000);  
  93.                 httpURLConnection.setDoInput(true);  
  94.                 httpURLConnection.setRequestMethod(“GET”);  
  95.                 int responseCode = httpURLConnection.getResponseCode();  
  96.                 if (responseCode == 200) {  
  97.                     inputStream = httpURLConnection.getInputStream();  
  98.                 }  
  99.             }  
  100.         } catch (MalformedURLException e) {  
  101.             // TODO Auto-generated catch block  
  102.             e.printStackTrace();  
  103.         } catch (IOException e) {  
  104.             // TODO Auto-generated catch block  
  105.             e.printStackTrace();  
  106.         }  
  107.         return inputStream;  
  108.   
  109.     }  
  110.     public static Bitmap readFile(String path){  
  111.         //读取解密后的图片  
  112.         File file=new File(path);  
  113.         System.out.println(“readFile: ”+path);  
  114.         Bitmap bitmap=null;  
  115.         if(file.exists()&&flag==0){  
  116.         bitmap =BitmapFactory.decodeFile(path);  
  117.         }  
  118.           
  119.         return bitmap;  
  120.     }         
  121. }  
<servlet-mapping>
    <servlet-name>JsonAction<rvlet-name>
    <url-pattern>/servlet/JsonAction</url-pattern>
<servlet-mapping> 
    10、tomcat的端口是8080,所以最后的地址就是
    skey请求地址:http://192.168.1.114:8080/jsonProject/servlet/jsonAction?action_flag=skey
    图片地址:http://192.168.1.114:8080/jsonProject/a.jpg
    视频地址:http://192.168.1.114:8080/jsonProject/tudou-skey.mp4
二、客户端
    1、json数据解析类
<pre name="code" class="java">package com.and.netease.json;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
import org.json.JSONArray;
import com.and.netease.domain.Skey;
import android.R.integer;


public class JsonParse {

    public static Skey getListPerson(String urlPath) throws Exception{
        Skey skey_video=new Skey();
        byte[] data=readParse(urlPath);
        String jsonString=new String(new String(data)); 
        JSONObject jsonObject=new JSONObject(jsonString);
        JSONObject personObject=jsonObject.getJSONObject("skey");
        skey_video.setName(personObject.getString("name"));
        skey_video.setSkey(personObject.getString("skey"));

        return skey_video;  
    }

    private static byte[] readParse(String urlPath) throws Exception{
        // TODO Auto-generated method stub
        ByteArrayOutputStream outStream=new ByteArrayOutputStream();
        byte[] data=new byte[1024];
        int len=0;
        URL url=new URL(urlPath);
        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(3000);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        conn.connect();
        int responseCode=conn.getResponseCode();
        if(responseCode==200){
        InputStream inStream=conn.getInputStream();

        while ((len=inStream.read(data))!=-1) {
            outStream.write(data, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
        }
        return null;
    }

}
    2、加密图片的解密和接收,就是把上一篇文章的本地demo移植过来 
<pre name="code" class="java">public class ImageAdapter {
        static int flag=1;
    public static Bitmap readBitmap(String url,String fileName) {

            String savePath="/mnt/sdcard/UCDownloads/";//手机本地存储路径
            String srcPath=savePath+fileName;
            FileUtils fileUtils =new FileUtils();
            try {
                InputStream inputStream=getInputStream(url);
                File file=fileUtils.write2SDFromInput("UCDownloads/", fileName, inputStream);//把图片以文件形式下载到手机
                flag=MyAESAlgorithm.fileDecrypt(srcPath, Constant.Skey, srcPath,1); //解密

            } catch (Exception e) {
                // TODO: handle exception
            }
            return readFile(srcPath);
    }


    public static InputStream getInputStream(String URL_PATH) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(URL_PATH);
            if (url != null) {
                httpURLConnection = (HttpURLConnection) url.openConnection();
                // 设置网络超时时间
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod("GET");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode == 200) {
                    inputStream = httpURLConnection.getInputStream();
                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return inputStream;

    }
    public static Bitmap readFile(String path){
        //读取解密后的图片
        File file=new File(path);
        System.out.println("readFile: "+path);
        Bitmap bitmap=null;
        if(file.exists()&&flag==0){
        bitmap =BitmapFactory.decodeFile(path);
        }

        return bitmap;
    }       
}


 
 
 
 



 
 

 
 


   

      

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值