项目中手机客户端要播放远程服务器的图片和视频,还要获取解密的密钥。所以做了一个demo
服务器端用的是Myeclipse+Tomcat+servlet+MySQL,密钥传输用的是json,用的是http协议。网络环境是手机和服务器(笔记本)都连接同一个无线路由器
一、服务器
1、在Myeclipse里配置Tomcat,百度一下就行,很简单。
2、新建一个web工程,如下,存了5张图片,一个视频和一个xml文本
3、在数据库中建立一张表,存放密钥
4、服务器端,数据库服务类
- 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();
- }
- }
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映射
- <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;
- }
- }
<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;
}
}