网络
需要联网权限:
<uses-permission android:name="android.permission.INTERNET"/>
联网属于耗时操作,需要在其它线程运行
——————————————————————————————————————————-
HttpURLConnection
private void lw(){
try {
String Value = "username=abc&password=123";
String GETpath = "http://www.baidu.com?username="+ URLEncoder.encode("abc", "utf-8") +"&password=" + URLEncoder.encode("123", "utf-8"); //GET方式提交数据 (URLEncoder提交中文字符需要指定编码)
String path = "http://www.baidu.com";
URL url = new URL(path); //创建URL对象 指定要访问的网址
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //HttpURLConnection对象(用于发送&接收数据)
conn.setRequestMethod("POST"); //设置连接方式 GET or POST 必须大写 默认GET
conn.setConnectTimeout(5000); //设置连接超时 5000毫秒
//conn.setUseCaches(false);?//POST请求不能使用缓存
//POST方式需要
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); //传输的内容的类型
conn.setRequestProperty("Content-Length",String.valueOf(Value.length())); //传输的内容的长度
conn.setDoOutput(true); //设置一个标记,允许输出
conn.getOutputStream().write(Value.getBytes("utf-8")); //提交数据
//conn.connect(); //连接????????好像不需要
int code = conn.getResponseCode(); //获取服务器返回的状态码 (200请求成功 404未找到 500服务器内部错误 206部分成功...)
if(code == 200){
InputStream in = conn.getInputStream(); //获取从服务器返回的流数据
final String value = ReadInputStream(in); //String类型
//Bitmap value = BitmapFactory.decodeStream(in);//图片类型 位图对象 通过位图工厂获取位图
runOnUiThread(new Runnable() { //在UI线程里执行action (不管在哪里都可以调用)
@Override
public void run() {
Toast.makeText(getApplicationContext(), "执行更新UI操作:"+value, 0);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String ReadInputStream(InputStream in) throws Exception { //定义一个方法,用来读取输入流的数据
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //内存输出流
int Len = 0;
byte buffer[] = new byte[1024]; //一次读1kb
while ((Len = in.read(buffer)) != -1) { //循环读流
baos.write(buffer, 0, Len);
}
in.close();
String value = new String(baos.toByteArray());
return value;
}
HttpClient
String GETpath = "http://www.baidu.com?username="+ URLEncoder.encode("abc", "utf-8") +"&password=" + URLEncoder.encode("123", "utf-8"); //GET方式提交数据 (URLEncoder提交中文字符需要指定编码)
String path = "http://www.baidu.com";
DefaultHttpClient client = new DefaultHttpClient(); //获取HttpClient实例
//GET
//HttpGet get = new HttpGet(GETpath); //使用GET方式
//HttpResponse response = client.execute(get); //执行GET请求
//POST
HttpPost post = new HttpPost(path);
java.util.List<NameValuePair> lists = new ArrayList<NameValuePair>();
lists.add(new BasicNameValuePair("name", "abc"));
lists.add(new BasicNameValuePair("password", "123"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(lists); //可以加个参数 编码格式
post.setEntity(entity); //倒着写比较好
HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode(); //获取服务器返回的状态码
if(code == 200){
InputStream in = response.getEntity().getContent(); //获取服务器返回的流
String value = ReadInputStream(in);
}
//mHttpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000); // Socket超时设置5s
//mHttpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 3000);// 连接超时3s
Socket通信
判断网络的连接
Context context = this.getApplicationContext();//获取应用上下文
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);//获取系统的连接服务
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();//获取网络的连接情况
if(activeNetInfo.getType()==ConnectivityManager.TYPE_WIFI){
//判断WIFI网
}else if(activeNetInfo.getType()==ConnectivityManager.TYPE_MOBILE) {
//判断3G网
}