基于Android前端与后台服务的项目中若干问题留份:
1. 文件收发:
Android 客户端:
import java.io.ByteArrayOutputStream;
import java.io.File ;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.commons.httpclient.HttpClient ;
import org.apache.commons.httpclient.HttpStatus ;
import org.apache.commons.httpclient.methods.PostMethod ;
import org.apache.commons.httpclient.methods.multipart.FilePart ;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity ;
import org.apache.commons.httpclient.methods.multipart.Part ;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Handler;
import android.os.Message;
public class HttpPicClient{
private static final int CHECK_MESSAGE_FINISHED=0x03;
private Message msg;
private String httpurl=null;
//private IdInfo myidinfo=null;
private Handler myHandler;
public void UpLoadFile ( String filepath,String serviceUrl)
{
String targetURL = null ;// TODO 指定URL
File targetFile = null ;// TODO 指定上传文件
targetFile = new File ( filepath) ;
targetURL = serviceUrl; // "http://10.10.10.158:8090/IDServer/TestServlet";servleturl
PostMethod filePost = new PostMethod ( targetURL ) ;
try
{
// 通过以下方法可以模拟页面参数提交
// filePost.setParameter("name", "中文");
// filePost.setParameter("pass", "1234");
Part [ ] parts =
{ new FilePart ( targetFile.getName ( ) , targetFile ) } ;
filePost.setRequestEntity ( new MultipartRequestEntity (
parts , filePost.getParams ( ) ) ) ;
HttpClient client = new HttpClient ( ) ;
client.getHttpConnectionManager ( ).getParams ( )
.setConnectionTimeout ( 5000 ) ;
int status = client.executeMethod ( filePost ) ;
if ( status == HttpStatus.SC_OK )
{
System.out.println ( "上传成功" ) ;
// 上传成功
}
else
{
System.out.println ( "上传失败" ) ;
// 上传失败
}
}
catch ( Exception ex )
{
ex.printStackTrace ( ) ;
}
finally
{
filePost.releaseConnection ( ) ;
}
}
public void queryDownloadFile(String IdNum,String url,Handler handler) {
myHandler=handler;
httpurl=url;
String IDNumber=IdNum;
HttpPost request = new HttpPost(httpurl);
// 先封装一个 JSON 对象
JSONObject param = new JSONObject();
try {
param.put("IDNumber", IDNumber);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 绑定到请求 Entry
StringEntity se=null;
try {
se = new StringEntity(param.toString(),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setEntity(se);
// 发送请求
HttpResponse httpResponse = null;
try {
httpResponse = new DefaultHttpClient().execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = httpResponse.getEntity();
InputStream is=null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len = 0;
try {
while((len=is.read(buffer))!=-1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] dataImage=bos.toByteArray();
try {
bos.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
msg = myHandler.obtainMessage(CHECK_MESSAGE_FINISHED, dataImage);//发送消息
myHandler.sendMessage(msg);
}
服务端:
1).收:
public class UploadFileController extends AbstractController {
private String successView;
private String failView;
private PersonService personService=new PersonServiceImpl();
public String getSuccessView() {
return successView;
}
public void setSuccessView(String successView) {
this.successView = successView;
}
public String getFailView() {
return failView;
}
public void setFailView(String failView) {
this.failView = failView;
}
private static final String HEAD_PIC="-HeadPic.bmp";
private static final String FINGER_PIC="-FingerPic.bmp";
//定义上传路径
private String uploadPath = "D:\\TempSpringMVCUploadFiles" ; // 上传文件的目录
public void init( ) throws ServletException
{
File uploadFile = new File ( uploadPath ) ;
if ( ! uploadFile.exists ( ) )
{
uploadFile.mkdirs ( ) ;
}
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
String rootfilePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
File uploadFile = new File ( rootfilePath ) ;
if ( ! uploadFile.exists ( ) )
{
uploadFile.mkdirs ( ) ;
}
System.out.println(rootfilePath);
//init();
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
//取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
//如果名称不为“”,说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
System.out.println(myFileName);
//重命名上传后的文件名
String fileName =file.getOriginalFilename();
File localFile = new File ( rootfilePath ,
fileName ) ;
file.transferTo(localFile);
/*
* 获取文件名信息并存储数据库索引以及文件
*/
String fileType=getFileType(fileName);
String fileID=getFileID(fileName);
String fileAbsolutePath=localFile.getAbsolutePath();
if(HEAD_PIC.equals(fileType)){
personService.insertPersonHeadPic(fileID, fileAbsolutePath);
System.out.println("update Head picture path:"+fileAbsolutePath+" success!");
}else if(FINGER_PIC.equals(fileType)){
personService.insertPersonFingerPic(fileID, fileAbsolutePath);
System.out.println("update Finger picture path:"+fileAbsolutePath+" success!");
}else{
System.out.println("file name error");
return null;
}
}
}
//记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
}
return new ModelAndView(getSuccessView());
}else{
return new ModelAndView(getFailView());
}
}
private String getFileID(String filename){
String ID=filename.substring(0,18);
return ID;
}
private String getFileType(String filename){
String Type=filename.substring(18);
return Type;
}
2)download:
@RequestMapping("/downloadFileByID.do") // 请求url地址映射,类似Struts的action-mapping
//接收前台传过来的字符串格式的json对象,在后台进行解析
public void queryPersonFile(HttpServletRequest request,HttpServletResponse response) throws IOException {
String JsonStr=null;
InputStream in=request.getInputStream();
JsonStr=IOUtils.toString(in,"UTF-8");
JSONObject Jobj=JSONObject.fromString(JsonStr);
String idnumber=Jobj.getString("IDNumber");
if(idnumber.equals(ID_temp)){
/*
* 回传图片文件
*/
getFileForDowload(response,headPicPath_temp);
}else{
System.out.println("请求ID不匹配");
return;
}
ID_temp=null;
headPicPath_temp=null;
String resultMsg="query person head picture success";
System.out.println(resultMsg);
}
protected void getFileForDowload(HttpServletResponse response,String filepath){
//response.setContentType("text/html;charset=UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String downLoadPath = filepath;
long fileLength = new File(downLoadPath).length();
try {
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos = new BufferedOutputStream(response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buff = new byte[1024];
int bytesRead;
try {
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bis.close();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
============================
2. Json消息交互:
1).Android:
public class HttpCheckInfoClient {
private static final int SAVE_MESSAGE=0x01;
private static final int CHECK_MESSAGE=0x02;
private static final int CHECK_MESSAGE_FINISHED=0x03;
private Message msg;
private String httpurl=null;
//private IdInfo myidinfo=null;
private Handler myHandler;
public void HttpSender(String IdNum,String url,Handler handler){
myHandler=handler;
httpurl=url;
String IDNumber=IdNum;
HttpPost request = new HttpPost(httpurl);
// 先封装一个 JSON 对象
JSONObject param = new JSONObject();
try {
param.put("IDNumber", IDNumber);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 绑定到请求 Entry
StringEntity se=null;
try {
se = new StringEntity(param.toString(),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* for Encoding Test
System.out.println(params);
System.out.println(se);
System.out.println(EntityUtils.toString(se,"iso-8859-1"));
System.out.println(EntityUtils.toString(se,"gb2312"));
System.out.println(EntityUtils.toString(se,"gbk"));
System.out.println(EntityUtils.toString(se,"utf-8"));
*/
request.setEntity(se);
// 发送请求
HttpResponse httpResponse = null;
try {
httpResponse = new DefaultHttpClient().execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 得到应答的字符串,这也是一个 JSON 格式保存的数据
String retSrc=null;
if(httpResponse==null){
msg = myHandler.obtainMessage(SAVE_MESSAGE, "网络异常");//发送消息
myHandler.sendMessage(msg);
return;
}
try {
retSrc = EntityUtils.toString(httpResponse.getEntity());
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 生成 JSON 对象
JSONObject result=null;
try {
result = new JSONObject( retSrc);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
IdInfo receiveIdinfo=new IdInfo();
JSONObject personObj=new JSONObject();
personObj = result.getJSONObject("Person");
receiveIdinfo.setInfo_Name(personObj.getString("name"));
receiveIdinfo.setInfo_Gender(personObj.getString("gender"));
msg = myHandler.obtainMessage(CHECK_MESSAGE, receiveIdinfo);//发送消息
myHandler.sendMessage(msg);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2)后台:
@RequestMapping("/checkPersonByID.do") // 请求url地址映射,类似Struts的action-mapping
//接收前台传过来的字符串格式的json对象,在后台进行解析
public void queryPersonObject(HttpServletRequest request,HttpServletResponse response) throws IOException {
String JsonStr=null;
InputStream in=request.getInputStream();
JsonStr=IOUtils.toString(in,"UTF-8");
JSONObject Jobj=JSONObject.fromString(JsonStr);
String idnumber=Jobj.getString("IDNumber");
Person resultPerson=null;
try {
resultPerson=personService.QueryPersonInfo(idnumber);
}catch (Exception e){
e.printStackTrace();
}
JSONObject resultParam=new JSONObject();
resultParam.put("name", resultPerson.getName());
resultParam.put("gender", resultPerson.getGender());
JSONObject rsultParams=new JSONObject();
rsultParams.put("Person", resultParam);
responseOutWithJson(response,rsultParams);
-------------------------------------------------------------------------------------
protected void responseOutWithJson(HttpServletResponse response,
JSONObject responseObject) {
//将实体对象转换为JSON Object转换
//JSONObject responseJSONObject = JSONObject.fromObject(responseObject);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(responseObject.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
=========================
3. Android 自定义Dialog显示消息和图片:
1)OwndefinedDialog.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:background="@color/white">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="38dp"
android:background="@drawable/dialog_title"
android:paddingTop="2dip"
android:text="数据库中返回信息"
android:gravity="center"
android:textColor="#000000" />
<LinearLayout
android:layout_width="301dp"
android:layout_height="173dp"
android:background="@drawable/dialog_body"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView3"
android:layout_width="3dp"
android:layout_height="match_parent"
android:layout_weight="0.00"
android:text=" " />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.01"
android:orientation="vertical" >
<TextView
android:id="@+id/textView4"
android:layout_width="133dp"
android:layout_height="3dp"
android:text=" " />
<TextView
android:id="@+id/dialog_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#000000" />
</LinearLayout>
<LinearLayout
android:layout_width="55dp"
android:layout_height="match_parent"
android:layout_weight="0.01"
android:orientation="vertical" >
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="3dp"
android:text=" " />
<ImageView
android:id="@+id/dialog_image"
android:layout_width="match_parent"
android:layout_height="113dp"
android:layout_weight="0.57" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="44dp"
android:orientation="vertical" >
<Button
android:id="@+id/dialog_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/btn_1"
android:gravity="center"
android:paddingTop="5dip"
android:text="确定" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:text=""
android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
2).values下的Style :添加
<style name="MyDialog" parent="@android:Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@color/silver</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
3). Dialog类:
import com.ID.recogid.R;
import com.cr30a.activity.ConnectActivity;
import com.cr30a.asynctask.AsyncFingerprint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MyOwnDialog extends Dialog {
Context context;
private TextView tv;
private ImageView iv;
private Button btn;
private String showmessage=null;
private Bitmap showimage=null;
public MyOwnDialog(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
}
public MyOwnDialog(Context context, int theme){
super(context, theme);
this.context = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.owndefineddialog);
tv=(TextView)findViewById(R.id.dialog_text);
iv=(ImageView)findViewById(R.id.dialog_image);
btn=(Button)findViewById(R.id.dialog_button);
tv.setText(showmessage);
iv.setBackgroundDrawable(new BitmapDrawable(showimage));
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyOwnDialog.this.dismiss();
}
});;
}
public void setParams(String msg,Bitmap image){
this.showmessage=msg;
this.showimage=image;
}
}
4)Activity调用:
MyOwnDialog dialog = new MyOwnDialog(IdReaderActivity.this,
R.style.MyDialog);
dialog.setParams(showMsg, thisHeadPic);
dialog.show();