Android客服端, 服务器和数据库简单交互之获取图片

来源:互联网 发布:python十分钟入门 编辑:程序博客网 时间:2024/05/02 11:55

大概思路: 数据库按编号保存图片的路径, 当客服端请求获取图片时, 服务器根据编号获取图片的保存路径, 并返回客服端, 客服端在根据此路径下载图片到本地


服务端:

GetPicServlet.class

public class GetPicServlet extends HttpServlet{private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/plain;charset=UTF-8");// 获取客服端请求参数String reqMessage = req.getParameter("request");int id = Integer.parseInt(req.getParameter("ID"));try {PrintWriter out = resp.getWriter();if(reqMessage.equals("GET_PIC")){System.out.println("返回报文: " + ConnectDB.getPicPath(id) );out.write(ConnectDB.getPicPath(id));out.close();}else{System.out.println("获取图片失败");out.close();}} catch (Exception e) {e.printStackTrace();}}}


连接数据库:

ConnectDB.class

public class ConnectDB {public final static String driver = "com.mysql.jdbc.Driver";public final static String url = "jdbc:mysql://localhost:3306/mydb";public final static String dbName = "root";public final static String dbPassword = "123";/** * 根据编号获取图片路径 * @param ID 编号 * @return 返回图片路径 */public static String getPicPath(int ID){String result = "";String sql = "select Path from t_images where NO = ?";Connection conn = null;PreparedStatement ps = null;try {// 加载驱动Class.forName(driver);conn = DriverManager.getConnection(url, dbName, dbPassword);ps = conn.prepareStatement(sql);ps.setInt(1, ID);ResultSet resultSet = ps.executeQuery();if(resultSet.next()){result = resultSet.getString("Path");}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally{try {if(ps != null){ps.close();}if(conn != null){conn.close();}} catch (SQLException e) {e.printStackTrace();}}return result;}}


客服端:

public class MainActivity extends Activity {Button downloadPic;ImageView image;Bitmap bitmap = null;private static final String SERVER_IP = "http://192.168.1.104:8080";private static final int REQUEST_TIMEOUT = 5 * 1000;    // 设置请求超时5秒钟private static final int SO_TIMEOUT = 10 * 1000;        // 设置等待数据超时时间10秒钟@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);image = (ImageView)findViewById(R.id.image);downloadPic = (Button)findViewById(R.id.btn_downloadPic);downloadPic.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {new DownloadPicTask().execute("GET_PIC", "10");}});}private class DownloadPicTask extends AsyncTask<String, Void, String>{@Overrideprotected String doInBackground(String... params) {String result = "";// 创建HttpPostHttpPost httpRequest = new HttpPost(SERVER_IP + "/GetPicServer/servlet/" + "GetPicServlet");// 创建请求参数List<NameValuePair> reqParams = new ArrayList<NameValuePair>();reqParams.add(new BasicNameValuePair("request", params[0]));reqParams.add(new BasicNameValuePair("ID", params[1]));try{// 设置请求参数httpRequest.setEntity(new UrlEncodedFormEntity(reqParams, HTTP.UTF_8));BasicHttpParams httpParams = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);HttpClient client = new DefaultHttpClient(httpParams);// 发送post请求HttpResponse httpResponse = client.execute(httpRequest);if(httpResponse.getStatusLine().getStatusCode() == 200){result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");result = SERVER_IP + "/GetPicServer/" + result;}}catch (Exception e) {e.printStackTrace();}return result;}@Overrideprotected void onPostExecute(final String result) {if(!result.equals(""))new Thread(){@Overridepublic void run() {bitmap = getPic(result);Message msg = new Message();msg.what = 0x001;msg.obj = bitmap;handler.sendMessage(msg);};}.start();}}/** * 从服务器获取图片 * @param uriPic 图片地址 * @return 返回Bitmap */private Bitmap getPic(String uriPic){URL imageUrl = null;Bitmap bitmap = null;try {imageUrl = new URL(uriPic);} catch (MalformedURLException e) {e.printStackTrace();}try {HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();InputStream in = conn.getInputStream();bitmap = BitmapFactory.decodeStream(in);in.close();} catch (IOException e) {e.printStackTrace();}return bitmap;}@SuppressLint("HandlerLeak")Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {if(msg.what == 0x001){image.setImageBitmap((Bitmap)msg.obj);}};};}

运行结果:

                   


注意事项: ** 图片要放在服务器的目录下


0 0
原创粉丝点击