`
Aina_hk55HK
  • 浏览: 386371 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Android HttpURLConnection网络通信

阅读更多
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="@string/hello" />
	<Button android:text="直接获取数据" android:id="@+id/Button01"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
	</Button>
	<Button android:text="GET方式传递" android:id="@+id/Button02"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
	</Button>
	<Button android:text="POST方式传递" android:id="@+id/Button03"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
	</Button>
	<Button android:text="获取图片" android:id="@+id/Button04"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
	</Button>
</LinearLayout>



package com.Aina.Android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Test extends Activity {
    /** Called when the activity is first created. */
	private Button btn1 = null;
	private Button btn2 = null;
	private Button btn3 = null;
	private Button btn4 = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn1 = (Button) this.findViewById(R.id.Button01);
        btn2 = (Button) this.findViewById(R.id.Button02);
        btn3 = (Button) this.findViewById(R.id.Button03);
        btn4 = (Button) this.findViewById(R.id.Button04);
        btn1.setOnClickListener(new Button.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(Test.this, ShowData.class);
				Bundle b = new Bundle();
				b.putInt("id", 1);
				intent.putExtras(b);
				startActivity(intent);
			}
        	
        });
        btn2.setOnClickListener(new Button.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(Test.this, ShowData.class);
				Bundle b = new Bundle();
				b.putInt("id", 2);
				intent.putExtras(b);
				startActivity(intent);
			}
        	
        });
        btn3.setOnClickListener(new Button.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(Test.this, ShowData.class);
				Bundle b = new Bundle();
				b.putInt("id", 3);
				intent.putExtras(b);
				startActivity(intent);
			}
        	
        });
        btn4.setOnClickListener(new Button.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(Test.this, ShowData.class);
				Bundle b = new Bundle();
				b.putInt("id", 4);
				intent.putExtras(b);
				startActivity(intent);
			}
        	
        });
    }
}




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView android:id="@+id/TextView_HTTP"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />
	<ImageView android:id="@+id/ImageView01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</ImageView>
</LinearLayout>


package com.Aina.Android;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * com.Aina.Android Pro_HttpURLConnection
 * 
 * @author Aina.huang E-mail: 674023920@qq.com
 * @version 创建时间:2010 Jul 12, 2010 2:08:40 PM 类说明
 */
public class ShowData extends Activity {
	private TextView tv = null;
	private ImageView iv = null;
	private Bitmap mBitmap = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http);
		Intent intent = this.getIntent();
		Bundle b = intent.getExtras();
		int id = b.getInt("id");
		tv = (TextView) this.findViewById(R.id.TextView_HTTP);
		iv = (ImageView) this.findViewById(R.id.ImageView01);
		if (id == 1) {
			String httpUrl = "http://192.168.0.132:8080/Android/http.jsp";
			URL url = null;
			try {
				url = new URL(httpUrl);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			if (url != null) {
				try {
					HttpURLConnection urlConn = (HttpURLConnection) url
							.openConnection();// 打开连接,此处只是创建一个实力,并没有真正的连接
					urlConn.connect();// 连接
					InputStream input = urlConn.getInputStream();
					InputStreamReader inputReader = new InputStreamReader(input);
					BufferedReader reader = new BufferedReader(inputReader);
					String inputLine = null;
					StringBuffer sb = new StringBuffer();
					while ((inputLine = reader.readLine()) != null) {
						sb.append(inputLine).append("\n");
					}
					reader.close();
					inputReader.close();
					input.close();
					urlConn.disconnect();
					if(sb !=null){
						tv.setText(sb.toString());
					}else{
						tv.setText("读取的内容:NULL");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				Log.i("TAG", "url is null");
			}
		}else if(id==2){
			String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp?par=hk";
			URL url = null;
			try {
				url = new URL(httpUrl);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			if (url != null) {
				try {
					HttpURLConnection urlConn = (HttpURLConnection) url
							.openConnection();// 打开连接,此处只是创建一个实力,并没有真正的连接
					urlConn.setDoInput(true);
					urlConn.setDoOutput(true);
					urlConn.connect();// 连接
					InputStream input = urlConn.getInputStream();
					InputStreamReader inputReader = new InputStreamReader(input);
					BufferedReader reader = new BufferedReader(inputReader);
					String inputLine = null;
					StringBuffer sb = new StringBuffer();
					while ((inputLine = reader.readLine()) != null) {
						sb.append(inputLine).append("\n");
					}
					reader.close();
					inputReader.close();
					input.close();
					urlConn.disconnect();
					if(sb !=null){
						tv.setText(sb.toString());
					}else{
						tv.setText("读取的内容:NULL");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				Log.i("TAG", "url is null");
			}
		}else if(id==3){
			String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";
			URL url = null;
			try {
				url = new URL(httpUrl);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			if (url != null) {
				try {
					HttpURLConnection urlConn = (HttpURLConnection) url
							.openConnection();// 打开连接,此处只是创建一个实力,并没有真正的连接
					urlConn.setDoInput(true);
					urlConn.setDoOutput(true);
					urlConn.setRequestMethod("POST");
					urlConn.setUseCaches(false);//post请求不能使用缓存.
					urlConn.setInstanceFollowRedirects(true);//是否自动重定向.
					urlConn.connect();// 连接
					OutputStream out = urlConn.getOutputStream();
					DataOutputStream data = new DataOutputStream(out);
					data.writeBytes("par="+URLEncoder.encode("hk", "GBK"));
					data.flush();
					data.close();
					out.close();
					InputStream input = urlConn.getInputStream();
					InputStreamReader inputReader = new InputStreamReader(input);
					BufferedReader reader = new BufferedReader(inputReader);
					String inputLine = null;
					StringBuffer sb = new StringBuffer();
					while ((inputLine = reader.readLine()) != null) {
						sb.append(inputLine).append("\n");
					}
					reader.close();
					inputReader.close();
					input.close();
					urlConn.disconnect();
					if(sb !=null){
						tv.setText(sb.toString());
					}else{
						tv.setText("读取的内容:NULL");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				Log.i("TAG", "url is null");
			}
		}else if(id==4){
			String httpUrl = "http://www.google.com.hk/intl/zh-CN/images/logo_cn.gif";
			URL url = null;
			try {
				url = new URL(httpUrl);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			if (url != null) {
				try {
					HttpURLConnection urlConn = (HttpURLConnection) url
							.openConnection();// 打开连接,此处只是创建一个实力,并没有真正的连接
					urlConn.connect();// 连接
					InputStream input = urlConn.getInputStream();
					mBitmap = BitmapFactory.decodeStream(input);
					if(mBitmap != null){
						iv.setImageBitmap(mBitmap);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				Log.i("TAG", "url is null");
			}
		}
	}
}



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.Aina.Android" android:versionCode="1"
	android:versionName="1.0">
	<application android:icon="@drawable/icon"
		android:label="@string/app_name">
		<activity android:name=".Test"
			android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category
					android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		<activity android:name=".ShowData"></activity>
	</application>
	<uses-permission android:name="android.permission.INTERNET" />

</manifest>

分享到:
评论
4 楼 759235384 2012-02-02  
写的很好诶
3 楼 zboracle 2011-09-27  
xqxmh 写道
怎么我把代码照搬,怎么还是没有用啊?请联系我Gxqxmh@gmail.com

呵呵 这个照搬是不可以的 至少他的url 是自己启动的一个tomcat服务器 
2 楼 xqxmh 2011-01-17  
怎么我把代码照搬,怎么还是没有用啊?请联系我Gxqxmh@gmail.com
1 楼 hezhou_0521 2010-11-10  
你的日志写得不错,不过代码里注释太少。

相关推荐

    Android网络通信(HttpURLConnection与HttpClient)、实时更新

    该压缩包中包含3个小程序,第一个是使用HttpURLConnection获取网络资源,包括直接获取、使用get方式获取、使用post方式获取、以及获得网络图片;第二个小程序是使用HttpClient获取网络资源,包括get方式和post方式;...

    Android网络技术HttpURLConnection详解

    主要为大家详细介绍了Android网络技术HttpURLConnection的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    客户端与服务器端通信示例代码(基于HttpURlConnection实现)

    本例演示最简单的android客户端和服务器端通信,客户端使用android4.0以上版本,服务器端为dynamic web project工程,使用时将client代码中的ip地址改为自己电脑的ipv4地址,同时保证手机和电脑处于同一网络下(内网...

    android http通信demo

    android 当中涉及到网络编程的部分经常会用到http通信,同时android也为我么您提供了HttpUrlConnection接口和HttpClient接口,大大的方便了开发。Http通信又分为两种方式:get和post,get可以uoqu静态页面,传入参数...

    FridaAndroid 07-爬虫之网络通信库HttpURLConnection示例程序 HttpURLConnect

    HttpURLConnectionDemo.apk

    使用HttpURLConnection

    HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。

    Android网络Http通信(及cmwap处理)

    HttpURLConnection和HttpClient接口的get post访问 cmwap下代理

    Android网络通信的实现方式

    Android网络编程分为两种:基于http协议的,和基于socket的。 基于Http协议:HttpClient、HttpURLConnection、AsyncHttpClient框架等 基于Socket: (1)针对TCP/IP的Socket、ServerSocket (2)针对UDP/IP的...

    Android移动开发-使用OkHttp读取网络资源的实现

    Android网络框架之OkHttp是一个...OkHttp不仅在接口封装上画面做的简单易用,就连在底层实现上也是自成一派,比起原生的HttpURLConnection可以说是有过之而无不及,现在已经成了广大Android开发者首选的网络通信库。

    Android通过HttpURLConnection和HttpClient接口实现网络编程

    Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。以下是学习中的一些经验。 1、HttpURLConnection接口  首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,...

    android开发揭秘PDF

    8.4 网络通信的中文乱码问题 8.5 WebKit应用 8.5.1 WebKjt概述 8.5.2 WebView浏览网页 8.5.3 WebView与Javascript 8.6 WtFi介绍 8.7 蓝牙 8.8 小结 第9章 Android特色开发 9.1 传感器 9.2 语音识别 9.3 GoogleMap ...

    Android的网络与通信应用程序设计PPT

    (1)理解HTTP协议、URL请示的类别 (2)理解并掌握Android的线程与Hander消息机制 (3)学会使用HttpURLConnection访问网络 (4)学会使用HttpClient访问网络

    谈谈Android的三种网络通信方式

    比如:创建URL,以及URLConnection/HttpURLConnection对象、设置链接参数、链接到服务器、向服务器写数据、从服务器读取数据等通信。这些在Java网络编程中均有涉及,我们看一个简单的socket编程,实现服务器回发客

    Android Volley Jar框架 v2017.3.17.zip

    于是乎,一些Android网络通信框架也就应运而生,比如说AsyncHttpClient,它把HTTP所有的通信细节全部封装在了内部,我们只需要简单调用几行代码就可以完成通信操作了。再比如Universal-Image-Loader,它使得在界面上...

    Android使用http协议与服务器通信的实例

    首先,需要明确一下http通信流程,Android目前提供两种http通信方式,HttpURLConnection和HttpClient,HttpURLConnection多用于发送或接收流式数据,因此比较适合上传/下载文件,HttpClient相对来讲更大更全能,但是...

    《Android应用开发揭秘》附带光盘代码.

     8.4 网络通信的中文乱码问题  8.5 WebKit应用  8.5.1 WebKjt概述  8.5.2 WebView浏览网页  8.5.3 WebView与Javascript  8.6 WtFi介绍  8.7 蓝牙  8.8 小结  第9章 Android特色开发  9.1 传感器  9.2 ...

    Android实验七.doc

    s 计算机科学与技术系 实 验 报 告 专业名称 计算机科学与技术 课程名称 Android嵌入式软件开发 项目名称 网络数据与服务 班 级 学 号 姓 名 同组人员 无 实验日期 2016.10.18 一、实验目的与要求: 【实验目的】 ...

    Android网络音乐播放器 源码下载

    该android音乐播放器支持以下功能: 1.本地音乐的播放控制; 2.音乐的收藏和取消收藏; 3.网络音乐的搜索和下载; 4.下载的控制-暂停/继续/删除/断点下载; 5.音乐列表刷新-下载完成后刷新可以看到新增歌曲; 6.播放...

    Android应用开发揭秘pdf高清版

    8.4 网络通信的中文乱码问题 8.5 WebKit应用 8.5.1 WebKjt概述 8.5.2 WebView浏览网页 8.5.3 WebView与Java 8.6 WtFi介绍 8.7 蓝牙 8.8 小结 第9章 Android特色开发 9.1 传感器 9.2 语音识别 9.3 GoogleMap 9.3.1 ...

    Android网络编程之使用OKHttp

    在Android中使用HttpURLConnection和OkHttp进行网络数据通信,详细介绍了原理和方法。

Global site tag (gtag.js) - Google Analytics