android 联网

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lyf_web2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />

<!-- 联网权限 -->
<uses-permission
android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.lyf_web2.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
--------------------------------------------------------------------------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >


<Button
android:id="@+id/ButtonConn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/ButtonConn"/>
<!-- @string 没有s -->

</RelativeLayout>
-----------------------------------------------------------------------------------------
package com.example.lyf_web2;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

//extends继承Activity
//implement OnClickListener类 (里面有onClick(View v))
public class MainActivity extends Activity implements OnClickListener {
//声明
Button ButtonConn=null; //声明按钮
//声明常量 网络路径
final String BASE_URL="http://teacher.dm5u.com/AndroidServers/AndroidData.asmx/QusestionPage";
Handler handler; //声明Handler

@Override //activity创建时调用(Bundle 保存实例状态 )
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//得到控件
ButtonConn=(Button)findViewById(R.id.ButtonConn);
ButtonConn.setOnClickListener(this); //设置监听当前 类对象

this.handler=new Handler(){ //创建一个Handler
@Override //复写 处理信息方法handleMessage(Message 消息)
public void handleMessage(Message msg) {
switch(msg.what){ //用户定义消息代码,以便收件人可以确定这消息是关于什么。每个处理器都有自己的name-space消息代码,所以您不需要担心你的冲突与其他处理程序。
case 1: //如果是1,将携带的消息(msg.obj)弹出来
Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(), "LYF_ERROR", 1).show();
break;
}
}
};

}

@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;
}

//自定义的post访问网络方法
//传入Handler是应为我们打算在不同的线程中去访问网络,而在新线程中只有Handler能处理主线程UI(原先的线程)
public void doPost(final Handler handler){
new Thread(){ //创建新线程
@Override //复写 运行方法
public void run() {
//查询字符串
String urlSelectString="startNum=1&endNum=6";
try {
//以网络路径创建URL对象
URL url=new URL(BASE_URL);
//url打开连接 得到HttpURLConnection对象
HttpURLConnection httpUrlConnection= (HttpURLConnection)url.openConnection();
httpUrlConnection.setConnectTimeout(5*1000); //HttpURLConnection设置超时 5s
httpUrlConnection.setRequestMethod("POST"); //HttpURLConnection设置请求方式
httpUrlConnection.setDoInput(true); //HttpURLConnection设置 做输入
OutputStream outputStream = httpUrlConnection.getOutputStream(); //HttpURLConnection得到输出流
outputStream.write(urlSelectString.getBytes()); //将查询字符串 写入到输出流中

int code= httpUrlConnection.getResponseCode(); //HttpURLConnection得到响应码
if(code==200){ //如果请求成功
//HttpURlConnection中得到一个输入流(此输入流以连接对象建立,此流代表 连接对象连接的资源)
InputStream inPutStream=httpUrlConnection.getInputStream();
byte[] bsBuffer=new byte[1024]; //创建一个字节数组缓冲区
int len=0;
//创建字节数组输出流(用于 将数组缓冲区 的数据写入到 输出流中)
ByteArrayOutputStream byteArrayOutPutStream=new ByteArrayOutputStream();
while((len=inPutStream.read(bsBuffer))!=-1){ // 》》 将输入流中 的数据读取到bs缓冲区中
// 这个方法是从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中
// 它是有返回值的,它返回读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1
// 就是当它返回-1的时候 数据已经复制完了 while循环终止程序结束
byteArrayOutPutStream.write(bsBuffer,0,len); //《《 以bs的长度从偏移量到结束点 将bs中的数据写到OutPutStream中
}
//总结Java中的流 :输入 (r大于》W)输出
String json=new String(byteArrayOutPutStream.toByteArray()); //将输出流中的数据转换为字节数组,在转成String
handler.sendMessage(handler.obtainMessage(1,json)); //将信息发送到 Handler
}

} catch (Exception e) {
Log.v("lyf", e.toString()); //

}
}
}.start(); //开始线程
}

@Override //点击时调用 onClick(View 视图对象)
public void onClick(View v) { //
switch(v.getId()){ //得到视图的id ??
case R.id.ButtonConn: //点击时在视图中的id是 ButtongConn的Id
doPost(handler); //执行 自定义的方法 并传入当前类(前面定义的)的handler
break;
default:
break;
}
}

}

原文地址:https://www.cnblogs.com/blogLYF/p/3951383.html