項目中手機客戶端要播放遠程服務器的圖片和視頻,還要獲取解密的密鑰。所以做了一個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();
}
}
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;
}
}