网络协议有Http和TCP/IP协议:
http协议:有get和post方法,区别(GET请求是从服务器上获取数据,POST请求是向服务器传送数据后再获取)
httpclient:android 6.0已经除名
httpurlconnection:未来主流
TCP/IP:Socket通信
//HttpUrlConnection操作之get方法:
URL url=new URL("http://.../aile?username=lisi&password=123456");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
InputStream inputStream=null;
BufferedReader reader=null;
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
final String result=reader.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
}
});
}
reader.close();
inputStream.close();
connection.disconnect();
//HttpUrlConnection操作之post方法:
URL url=new URL("http://.../aile");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
String data="username=lisi&password=123456";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.getBytes());
connection.connect();
InputStream inputStream=null;
BufferedReader reader=null;
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
final String result=reader.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
}
});
}
reader.close();
inputStream.close();
connection.disconnect();
//HttpClient操作(android6.0后被淘汰,请尊重现实,仅参考):
public class HttpService {
public static final int METHOD_GET = 1;
public static final int METHOD_POST = 2;
//请求http服务端指定资源,并返回该资源的响应实体对象
public HttpEntity getEntity(String uri, List<NameValuePair> params,
int method) throws ConnectTimeoutException, IOException {
HttpEntity entity = null;
if (uri != null && uri.length() > 0) {
// 创建客户端对象
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
// 创建请求对象
HttpUriRequest request = null;
switch (method) {
case METHOD_GET:
StringBuilder sb = new StringBuilder(uri);
// 如果请求参数集合不为空,则拼接uri
if (params != null && !params.isEmpty()) {
sb.append('?');
for (NameValuePair pair : params) {
sb.append(pair.getName()).append('=').append(
pair.getValue()).append('&');
}
sb.deleteCharAt(sb.length() - 1);
}
// 创建请求对象
request = new HttpGet(sb.toString());
break;
case METHOD_POST:
request = new HttpPost(uri);
// 如果请求参数集合不为空,则设置请求实体
if (params != null && !params.isEmpty()) {
UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(
params);
((HttpPost) request).setEntity(reqEntity);
}
break;
}
// 执行请求,获得响应对象
HttpResponse response = client.execute(request);
// 判断状态码,如果请求成功,则获取实体输入流
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
}
}
return entity;
}
//获取实体对象的长度
public long getLength(HttpEntity entity) {
if (entity != null)
return entity.getContentLength();
return 0;
}
//解析实体对象,返回包含内容的字节数组
public byte[] getBytes(HttpEntity entity) throws IOException {
if (entity != null)
return EntityUtils.toByteArray(entity);
return null;
}
//将实体对象内容解析为字符串返回
public String getString(HttpEntity entity) throws IOException {
if (entity != null)
return EntityUtils.toString(entity);
return null;
}
public InputStream getStream(HttpEntity entity) throws IOException {
if (entity != null)
return entity.getContent();
return null;
}
}
基于tcp的协议的socket编程范例:(客户端和服务器端socket基础通讯)
客户android端:
1:activity:界面
public class MainActivity extends Activity {
Socket socket = null;
String buffer = "";
TextView txt1;
Button send;
EditText ed1;
String geted1;
public Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x11) {
Bundle bundle = msg.getData();
txt1.append("server:" + bundle.getString("msg") + "\n");
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1 = (TextView) findViewById(R.id.txt1);
send = (Button) findViewById(R.id.send);
ed1 = (EditText) findViewById(R.id.ed1);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
geted1 = ed1.getText().toString();
txt1.append("client:" + geted1 + "\n");
//启动线程 向服务器发送和接收信息
new MyThread(geted1).start();
ed1.getText().clear();
}
});
}
class MyThread extends Thread {
public String txt1;
public MyThread(String str) {
txt1 = str;
}
@Override
public void run() {
//定义消息
Message msg = new Message();
msg.what = 0x11;
Bundle bundle = new Bundle();
bundle.clear();
try {
//连接服务器 并设置连接超时为5秒
socket = new Socket();
socket.connect(new InetSocketAddress("192.168.0.102", 30000), 5000);
//向服务器发送信息
OutputStream ou = socket.getOutputStream();
ou.write(("android client:" + txt1).getBytes("gbk"));
ou.flush();
BufferedReader bff = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
//读取发来服务器信息
String line = null;
buffer = "";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}
bundle.putString("msg", buffer.toString());
msg.setData(bundle);
myHandler.sendMessage(msg);
bff.close();
ou.close();
socket.close();
} catch (SocketTimeoutException aa) {
//连接超时 在UI界面显示消息
bundle.putString("msg", "服务器连接失败!请检查网络是否打开");
msg.setData(bundle);
//发送消息 修改UI线程中的组件
myHandler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2:manifext.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aile.client">
<uses-permission
android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3:layout布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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="com.aile.client.MainActivity">
<EditText
android:id="@+id/ed1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="给服务器发送信息"/>
<Button
android:id="@+id/send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ed1"
android:text="发送"/>
<TextView
android:id="@+id/txt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/send"/>
</RelativeLayout>
服务器端:新建类
public class AndroidService {
public static void main(String[] args) throws IOException {
ServerSocket serivce = new ServerSocket(30000);
while (true) {
//等待客户端连接
Socket socket = serivce.accept();
new Thread(new AndroidRunable(socket)).start();
}
}
public static class AndroidRunable implements Runnable {
Socket socket = null;
public AndroidRunable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// 向android客户端输出hello worild
String line = null;
InputStream input;
OutputStream output;
String str = "你好!";
try {
//向客户端发送信息
output = socket.getOutputStream();
input = socket.getInputStream();
BufferedReader bff = new BufferedReader(
new InputStreamReader(input));
output.write(str.getBytes("gbk"));
output.flush();
//半关闭socket
socket.shutdownOutput();
//获取客户端的信息
while ((line = bff.readLine()) != null) {
System.out.print(line);
}
//关闭输入输出流
output.close();
bff.close();
input.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
大功告成,望采纳