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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Leo_eight/article/details/50528120

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


服务端:

GetPicServlet.class

public class GetPicServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected 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秒钟
	
	@Override
	protected 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() {	
			@Override
			public void onClick(View v) {
				new DownloadPicTask().execute("GET_PIC", "10");
			}
		});
	}
	
	private class DownloadPicTask extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... params) {
			String result = "";
			// 创建HttpPost
			HttpPost 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;
		}
		
		@Override
		protected void onPostExecute(final String result) {
			if(!result.equals(""))
			new Thread(){
				@Override
				public 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(){
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == 0x001){
				image.setImageBitmap((Bitmap)msg.obj);
			}
		};
	};
}

运行结果:

                   


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


猜你喜欢

转载自blog.csdn.net/Leo_eight/article/details/50528120