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

首先写一个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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值