Android基础学习之Socket、Http、Json网络编程
android 网络编程api
1.java.net包
2.org.apache.http包
3.android.net包
4.用框架 volley
使用类型:
1.做基本socket通信
2.访问web资源
主要类:
java.net包
Socket/ServerSocket 通信
URL
URLConnection
HttpURLConnection
org.apache.http包
核心接口:HttpClient 实现http客户端,具有浏览器的基本功能,但不能对页面进行解析和显示。可实现http连接管理。
实现类:
AndroidHttpClient
DefaultHttpClient
重载大量的execute()
final HttpResponse execute(HttpUriRequest request) //request封装请求参数
//返回一个响应的对象
HttpUriRequest接口
URL请求方式:
1.get请求(默认):会在url后面附加参数,如 http://…./?username=rose&password=123&key=value
HttpGet 类
java.lang.Object
org.apache.http.message.AbstractHttpMessage
org.apache.http.client.methods.HttpRequestBase
org.apache.http.client.methods.HttpGet
2.post请求:不会url后面附加参数,打包请求参数,不能看到打包数据 更安全
HttpPost 类
java.lang.Object
org.apache.http.message.AbstractHttpMessage
org.apache.http.client.methods.HttpRequestBase
org.apache.http.client.methods.HttpEntityEnclosingRequestBase
org.apache.http.client.methods.HttpPost
HttpEntity 接口用来封装post请求参数的对象
实现类:UrlEncodedFormEntity
UrlEncodedFormEntity(List< ? extends NameValuePair> parameters, String encoding)
NameValuePair接口
BasicNameValuePair实现类
使用流程:
1.创建httpclient对象
2.设置参数和请求属性
3.获得httpresponse对象进行操作
注意:
1.添加网络访问权限
2.Caused by: android.os.NetworkOnMainThreadException 错误
从Honeycomb SDK(3.0)开始,google不再允许网络请求(HTTP、Socket)等相关操作直接
在Main Thread类中,其实本来就不应该这样做,直接在UI线程进行网络操作,会阻塞UI。
所以,也就是说,在Honeycomb SDK(3.0)以下的版本,你还可以继续在Main Thread里这样做,在3.0以上,就不行了,建议使用异步操作方式:
Handler handler=new Handler(){
handleMessage(){
//更新UI代码
}
};
onCreate(){
new Thread(){
run(){
connection();
//更新UI
handler.sendMessage(msg;
}
}
connection(){
//网络请求可能阻塞的情况
}
}
1.Socket部分
更多socket例子请移步:JAVA基础学习之TCP网络编程
示例:
活动客户端:
public class MainActivity extends Activity {
protected static final int CONNECTOK = 0;
protected static final int CONNECTFAIL = 1;
protected static final int READOK = 2;
protected static final int READFAIL = 3;
Button btn;
EditText edit;
TextView txt;
InputStream is=null;
OutputStream os=null;
DataInputStream dis=null;
DataOutputStream dos=null;
Socket socket;
Handler hanlder=new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case CONNECTOK:
Toast.makeText(MainActivity.this, "服务器连接成功!", Toast.LENGTH_SHORT).show();
break;
case CONNECTFAIL:
Toast.makeText(MainActivity.this, "服务器连接失败!", Toast.LENGTH_SHORT).show();
break;
case READOK:
Toast.makeText(MainActivity.this, "读服务器成功!", Toast.LENGTH_SHORT).show();
break;
case READFAIL:
Toast.makeText(MainActivity.this, "读服务器失败!", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit=(EditText)findViewById(R.id.editText1);
btn=(Button)findViewById(R.id.button1);
txt=(TextView)findViewById(R.id.textView1);
connectServer();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Login();
}
});
}
private void connectServer() {
final ProgressDialog dialog=new ProgressDialog(this);
dialog.setTitle("连接提示");
dialog.setMessage("正在连接服务器,请稍后...");
dialog.show();
new Thread(){
public void run() {
try {
socket=new Socket("192.168.7.5",2345);//阻塞点
is=socket.getInputStream();
os=socket.getOutputStream();
//连接到socket的输出流os,用DataOutputStream包装
dos=new DataOutputStream(os);
dis=new DataInputStream(is);
hanlder.sendEmptyMessage(CONNECTOK);
} catch (UnknownHostException e) {
e.printStackTrace();
hanlder.sendEmptyMessage(CONNECTFAIL);
} catch (IOException e) {
e.printStackTrace();
hanlder.sendEmptyMessage(CONNECTFAIL);
}
dialog.dismiss();
}
}.start();
}
protected void Login() {
new Thread(){
public void run() {
//将数据发送到server端
try {
dos.writeUTF(edit.getText().toString().trim());
dis=new DataInputStream(is);
String input=dis.readUTF();//阻塞点
txt.setText(input);
hanlder.sendEmptyMessage(READOK);
} catch (IOException e) {
e.printStackTrace();
hanlder.sendEmptyMessage(READFAIL);
}
}
}.start();
}
}
服务器端,java控制台程序:
public class Server {
public static void main(String[] args) {
ServerSocket srv=null;
Socket client=null;
InputStream is=null;
OutputStream os=null;
DataInputStream dis=null;
DataOutputStream dos=null;
try {
System.out.println("my server have started....");
srv=new ServerSocket(2345);
client=srv.accept();
is=client.getInputStream();
os=client.getOutputStream();
dis=new DataInputStream(is);
dos=new DataOutputStream(os);
//读客户端发送来的数据
String output=null;
String pwd=dis.readUTF();
if("123456".equals(pwd)){
output="welecome you!!!";
}else{
output="you can not visit my server!!!";
}
dos.writeUTF(output);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
dos.close();
dis.close();
is.close();
os.close();
client.close();
srv.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("my server have shutdown....");
}
}
}
2.Http部分
主要用于下载web网络资源或和网络服务器进行交互。
更多http例子请移步:JAVA基础学习之Http(含JSON)网络编程
URL类
URL url=new URL(“http://…..”);
InputStream is=url.openStream();
URLConnection con=openConnection(); //协议无关连接对象
HttpURLConnection con=openConnection();//http协议连接对象 请求/响应头信息
用法:
URL url = new URL("http://www.android.com/...");//URL对象和网络资源url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();//打开连接
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());//得到资源
readStream(in);//读取资源的方法
finally {
urlConnection.disconnect();//关闭连接
}
示例1:
1.1使用线程和消息,访问网络,下载图片和音乐
1.xml布局
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop=