Android通过HttpURLConnection类进行网络通信,获取网络图片

本文提供了使用Java的HttpURLConnection类通过GET和POST方式获取网络资源的示例,包括HTTP请求处理、图片获取及代码实现细节。

Http通信中使用的最多的是Get和Post。Get请求可以获取静态页面,也可以把参数放在url字符串后面传递给服务器。Post与Get的不同之处在于Post的参数不是放在url字符串里面,而是放在http请求数据中。HttpURLConnection是Java的标准类,继承自URLConnection类,URLConnection与 HttpURLConnection都是抽象类,去、、无法直接实例化对象。其对象主要通过URL的openConnection方法获得。下面就两种方式分别提供示例:

其中有两个资源文件,两个jsp的内容分别如下:
http.jsp
<html>
  <head> 
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  <body>
    <%
    	out.println("<h1>HTTP TEST<br/>http test</h1>");
     %>
  </body>
</html>
httpGet.jsp
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head> 
  <body>
    <%
    	String type = request.getParameter("par");
    	String result = new String(type.getBytes("iso-8859-1"),"gb2312");
    	out.println("<h1>parameters:"+result+"</h1>");
     %>
  </body>
</html>

1、  HttpURLConnection 类通过Get方式获取网络资源:

public class GetActivity extends Activity {
	private String TAG = "GetActivity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http);
		TextView textView = (TextView)findViewById(R.id.text);
		
		String urlString = "http://127.0.0.1:8080/test/httpGet.jsp?par=test";//http地址
		String resultData = "";//获得的数据
		URL url = null;
		try {
			url = new URL(urlString);//构造一个url对象
		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException");
			e.printStackTrace();
		}
		if(url!=null){
			try {
				HttpURLConnection urlConnection;//使用HttpURLConnection打开连接
				urlConnection = (HttpURLConnection)url.openConnection();
				InputStream stream = urlConnection.getInputStream();//得到读取的内容
				InputStreamReader in = new InputStreamReader(stream);
				BufferedReader buffere = new BufferedReader(in);	//为输出创建BufferedReader
				String line = null;
				while((line = buffere.readLine()) != null){//使用while循环来取得获取的数据
					resultData += line + "\n";//我们要在每一行的后面加上一个反斜杠来换行
				}
				if(resultData.equals("")){
					textView.setText("没取到数据");
				}else{
					textView.setText(resultData);
				}
				in.close();//关闭InputStreamReader
				urlConnection.disconnect();//关闭http连接
			} catch (IOException e) {
				Log.e(TAG, "IOException");
				e.printStackTrace();
			}
		}else{
			Log.e(TAG, "url null");
		}
	}
}

2、 HttpURLConnection 类通过Post方式获取网络资源:

public class PostActivity extends Activity {

	private String TAG="PostActivity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http);
		TextView textView = (TextView)findViewById(R.id.text);
		
		String httpUrl = "http://127.0.0.1:8080/test/httpGet.jsp";
		String resultData = "";
		URL url = null;
		try {
			url = new URL(httpUrl);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			Log.e(TAG, "MalformedURLException");
			e.printStackTrace();
		}
		if(url!=null){
			//使用HttpURLConnection打开连接
			HttpURLConnection urlConnection;
			try {
				urlConnection = (HttpURLConnection)url.openConnection();
				//因为这个是post请求,需要设置为true
				urlConnection.setDoOutput(true);
				urlConnection.setDoInput(true);
				//设置以Post方法
				urlConnection.setUseCaches(false);
				urlConnection.setInstanceFollowRedirects(true);
				//配置本次连接的Content-type
				urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				//从url.openConnection()至此的配置必须在connect之前完成,要注意的是:
				//connection.getOutputStream会隐含的进行connect
				urlConnection.connect();
				//DataOutputStream流
				DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
				//要上传的参数
				String content = "par=" + URLEncoder.encode("ABCD", "gb2312");
				//将要上传的内容写入流中
				outputStream.writeBytes(content);
				//刷新,关闭
				outputStream.flush();
				outputStream.close();
				//取得数据
				BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
				String line = null;
				//使用循环体来获得数据
				while((line = reader.readLine())!=null){
					resultData += line + "\n";
				}
				if(!resultData.equals("")){
					textView.setText(resultData);
				}else{
					textView.setText("读取的内容为null");
				}
				reader.close();
				//关闭http连接
				urlConnection.disconnect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e(TAG, "IOException");
				e.printStackTrace();
			}
		}else{
			Log.e(TAG, "url null");
		}
	}
}

3、获取网络图片的代码:

public class ImageActivity extends Activity {

	private String TAG = "ImageActivity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image);
		ImageView imageView = (ImageView)findViewById(R.id.image);
		Button button = (Button)findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ImageActivity.this, MainActivity.class);
				startActivity(intent);
			}
		});
		String urlString = "http://www.eoeandroid.com/data/attachment/forum/201107/18/142935bbi8d3zpf3d0dd7z.jpg";
		URL imageUrl = null;
		Bitmap bitmap = null;
		try{
			imageUrl = new URL(urlString);
		}catch (MalformedURLException e) {
			// TODO: handle exception
			Log.e(TAG, "MalformedURLException");
			e.printStackTrace();
		}
		try{
			HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
			connection.setDoInput(true);
			connection.connect();
			//将得到的数据转换为InputStream
			InputStream is = connection.getInputStream();
			//将InputStream转换为Bitmap
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		}catch (IOException e) {
			// TODO: handle exception
			Log.e(TAG, "IOException");
		}
		if(bitmap == null){
			Log.i(TAG, "没取到数据");
		}else{
			imageView.setImageBitmap(bitmap);
		}
	}
	
}
注意:代码中的url地址中的ip:127.0.0.1需要修改成自己所需要的地址

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值