Android基础之文件下载Code,基础后台Servelet代码
本章包含:
1. 客户端通过HttpUrlConnection请求网络,
2. 基础的服务端servelet代码,
3. 基本的客户端文件下载代码,
4. 如何在配置文件中添加删除垃圾文件。
一:URL Code
String name= usernameView .getText().toString();
String password=passwordView.getText().toString();
InputStream is=null;
try {
StringBuilder sb=new StringBuilder("http://localhost:8080/httpCase/RegisterServlet?");
sb.append("username=");
sb.append(name);
sb.append("&password");
sb.append(password);
URL url=new URL(new String(sb));//对地址进行编码(中文) String encoder = URLEncoder.encode(new String(sb),"UTF-8");
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(15*1000);
conn.setConnectTimeout(15*1000);//conn.setRequestProperty("apikey", "1c701e0a5633393ec2b661782434f314");
if(conn.getResponseCode()==200){
is=conn.getInputStream();
int lenth=0;
byte[] buf=new byte[1024];
ByteArrayOutputStream baos= new ByteArrayOutputStream();
while((lenth=is.read(buf))!=- 1){
baos.write(buf, 0,lenth);
}
String result=new String(baos.toByteArray());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
二:注册服务器
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.citsin;
import java.beans.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Citsin
*/
public class Regist extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
//保存到数据库
Connection conn = SingleDb.getInstance().getConnetion();
PreparedStatement prep = conn.prepareStatement(
"insert into people values (?, ?);");
prep.setString(1, username);
prep.setString(2, password);
prep.executeUpdate();
out.print("注册成功");
} catch (SQLException ex) {
Logger.getLogger(Regist.class.getName()).log(Level.SEVERE, null, ex);
out.print("注册失败");
}
//
//
// try (PrintWriter out = response.getWriter()) {
// /* TODO output your page here. You may use following sample code. */
// out.println("<!DOCTYPE html>");
// out.println("<html>");
// out.println("<head>");
// out.println("<title>Servlet Regist</title>");
// out.println("</head>");
// out.println("<body>");
// out.println("<h1>Servlet Regist at " + request.getContextPath() + "</h1>");
// out.println("</body>");
// out.println("</html>");
// }
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
三:登陆服务器
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.citsin;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Citsin
*/
public class Login extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
//保存到数据库
Connection conn = SingleDb.getInstance().getConnetion();
PreparedStatement prep = conn.prepareStatement(
"select * from people where username=? and password=? ;");
prep.setString(1, username);
prep.setString(2, password);
ResultSet rs = prep.executeQuery();
if(rs.next()){
out.print("登录成功");
}else{
out.print("登录失败");
}
} catch (SQLException ex) {
Logger.getLogger(Regist.class.getName()).log(Level.SEVERE, null, ex);
out.print("登录失败");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
四:数据库的单例模式
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.citsin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Citsin
*/
public class SingleDb {
private final static SingleDb INSTANCE = new SingleDb();
private Connection conn;
private SingleDb(){
try {
//保存到数据库
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stat = (Statement) conn.createStatement();
stat.executeUpdate("drop table if exists people;");
stat.executeUpdate("create table people (username, password);");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Regist.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(SingleDb.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Connection getConnetion(){
return conn;
}
public static SingleDb getInstance(){
return INSTANCE;
}
}
文件下载code
package com.example.yangjie.filedowload;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private AsyncFile filedownload ;
private ProgressDialog mProgressDialog ;//像上图那样的效果图
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onViewClick(View v){
File file=getExternalFilesDir(null);
String url="http://10.7.154.201:8080/teach/tools/JAVA_API_1.7.chm" ;
filedownload =new AsyncFile(url,file);
filedownload .execute();
}
public class AsyncFile extends AsyncTask<Void,Integer,File>{
private String url;
private File mfile;
public AsyncFile(String url, File mfile) {
this.url = url;
this.mfile = mfile;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog=new ProgressDialog(MainActivity. this);
mProgressDialog.setMessage("正在下载中...........");
mProgressDialog.show();
}
@Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
mProgressDialog.dismiss();
}
@Override
protected File doInBackground(Void... params) {
try {
URL url=new URL(this.url);
HttpURLConnection coon=(HttpURLConnection)url.openConnection();
FileOutputStream fos=new FileOutputStream( new File(mfile,"JAVA_API_1.7.CHM"));
/*coon.setReadTimeout(15*1000);
coon.setConnectTimeout(15*1000);
coon.setRequestProperty("apikey", " 6b6faae177cca41654a6045baa8f65a4" );*/
if(coon.getResponseCode()== 200){
InputStream is=coon.getInputStream();
int len=0;
int totalyleng=coon.getContentLength();
int read=0;
byte[] buf=new byte[1024];
while ((len=is.read(buf))!=- 1){
fos.write(buf, 0,len);
read=read+len;
publishProgress(totalyleng,read);//转换到onProgressUpdate 方法中去
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mProgressDialog.setMessage("下载了"+ ( float)values[ 1]/( float)values[ 0] *100+ "%");
}
}
}
删除Android中的垃圾文件
在build.gradle(Moudle.app)中加入以下代码,就可以删除Android App中的垃圾文件
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
}