关闭

用Java后台+Android_写一个简单的HttpConnection

48人阅读 评论(0) 收藏 举报
分类:

首先写一个Java后台的图片上传,吧图片上传到服务器,代码如下:


package ttt.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Image")
public class Image extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String type = request.getParameter("type");
		if ((type==null)||(type.equalsIgnoreCase(""))) {
			type="1";
		}
		String id = request.getParameter("id");
		if ((id==null)||(id.equalsIgnoreCase(""))) {
			id="1";
		}
		FileInputStream fis=new FileInputStream(
				this.getServletContext().getRealPath("")+"/images/png"+type+id+".jpg");
		byte[] b=new byte[fis.available()];
		fis.read(b);
		fis.close();
		
		response.setContentType("application/octet-stream");
		ServletOutputStream op = response.getOutputStream();
		op.write(b);
		op.close();
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


然后用Android写代码实现后台图片的获取和显示。


package com.gdqy.demo;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener{

	private ImageView iv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        iv = (ImageView)this.findViewById(R.id.id_img);
        Button btn_1=(Button)this.findViewById(R.id.id_btn_1);
        btn_1.setOnClickListener(this);
        Button btn_2=(Button)this.findViewById(R.id.id_btn_2);
        btn_2.setOnClickListener(this);
        Button btn_3=(Button)this.findViewById(R.id.id_btn_3);
        btn_3.setOnClickListener(this);
        Button btn_4=(Button)this.findViewById(R.id.id_btn_4);
        btn_4.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (checkNetworkState()!=true) {
			Toast.makeText(this, "网络没有打开,请打开网络后再试试", Toast.LENGTH_LONG).show();
			return;
		}
		int id = v.getId();
		switch (id) {
		case R.id.id_btn_1:
			downLoadImageAndShow(1,1);
			break;
		case R.id.id_btn_2:
			downLoadImageAndShow(1,2);
			break;
		case R.id.id_btn_3:
			downLoadImageAndShow(2,1);
			break;
		case R.id.id_btn_4:
			downLoadImageAndShow(2,2);
			break;
		}
	}

	private boolean checkNetworkState() {
		// TODO Auto-generated method stub
		ConnectivityManager cm=(ConnectivityManager)this.getSystemService(MainActivity.CONNECTIVITY_SERVICE);
		NetworkInfo ni=cm.getActiveNetworkInfo();
		if((ni==null)||(ni.isConnected()==false)){
			return false;
		}
		return true;
	}
	
	private void downLoadImageAndShow(int type, int id) {
		// TODO Auto-generated method stub
		new MyAsyncTask().execute("本机的图片地址?type="+type+"&"+"id="+id);
	}
	private class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
			}
			@Override
			protected void onProgressUpdate(Void... values) {
				// TODO Auto-generated method stub
				super.onProgressUpdate(values);
			}
			@Override
			protected void onPostExecute(Bitmap bm) {
				// TODO Auto-generated method stub
				iv.setImageBitmap(bm);
			}
				@Override
			protected Bitmap doInBackground(String... params) {
				// TODO Auto-generated method stub
					URL url;
					HttpURLConnection urlConnection = null;
					Bitmap bm = null;
					try {
						url = new URL(params[0]);
						urlConnection = (HttpURLConnection)url.openConnection();
						urlConnection.setRequestMethod("GET");
						urlConnection.connect();
						if (urlConnection.getResponseCode()!=HttpURLConnection.HTTP_OK) {
							urlConnection.disconnect();
							return null;
						}
						byte[] b =new byte[2048];
						ByteArrayOutputStream baos=new ByteArrayOutputStream();
						BufferedInputStream in= new BufferedInputStream(urlConnection.getInputStream());
						
						int len = 0;
						while ((len = in.read(b))>0) {
							baos.write(b, 0, len);
							
						}
						bm = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());
						baos.close();
						in.close();
					} catch (MalformedURLException e) {
						// TODO: handle exception
						return null;
					}catch (IOException e) {
						// TODO: handle exception
						return null;
					}
					finally{
						urlConnection.disconnect();
					}
				return bm;
			}
	}

}

最后显示在模拟器上的程序:



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2149次
    • 积分:137
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:0篇
    • 译文:1篇
    • 评论:0条
    文章分类
    文章存档