<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="数据存储方式"
android:textColor="#ff0000"
android:textSize="20sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickSP"
android:text="SharedPreference存储" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickIF"
android:text="内部文件存储" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickOF"
android:text="外部文件存储" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickDB"
android:text="数据库存储" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickNW"
android:text="网络存储存储" />
</LinearLayout>
1.1 主界面Activity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// 测试sp存储
public void onClickSP(View v) {
startActivity(new Intent(this, SpActivity.class));
}
// 测试手机内部文件存储
public void onClickIF(View v) {
startActivity(new Intent(this, IFActivity.class));
}
// 测试手机外部文件存储
public void onClickOF(View v) {
startActivity(new Intent(this, OFActivity.class));
}
// 测试Sqlite数据库存储
public void onClickDB(View v) {
startActivity(new Intent(this, DBActivity.class));
}
public void onClickNW(View v) {
startActivity(new Intent(this, NetworkActivity.class));
}
}
2. sp存储XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et_sp_key"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="存储的key" />
<EditText
android:id="@+id/et_sp_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="存储的value" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="save"
android:text="保 存" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="read"
android:text="读 取" />
</LinearLayout>
</LinearLayout>
2.2 sp存储Activity
/**
* 测试sp存储的界面
*/
public class SpActivity extends Activity {
private EditText et_sp_key;
private EditText et_sp_value;
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sp);
et_sp_key = (EditText) findViewById(R.id.et_sp_key);
et_sp_value = (EditText) findViewById(R.id.et_sp_value);
//1. 得到sp对象
sp = getSharedPreferences("atguigu", Context.MODE_PRIVATE);
}
public void save(View v) {
//2. 得到editor对象
Editor edit = sp.edit();
//3. 得到输入的key/value
String key = et_sp_key.getText().toString();
String value = et_sp_value.getText().toString();
//4. 使用editor保存key-value
edit.putString(key, value).commit();
//5. 提示
Toast.makeText(this, "保存完成!", 0).show();
}
public void read(View v) {
//1. 得到输入的key
String key = et_sp_key.getText().toString();
//2. 根据key读取对应的value
String value = sp.getString(key, null);
//3. 显示
if(value==null) {
Toast.makeText(this, "没有找到对应的value", 0).show();
} else {
et_sp_value.setText(value);
}
}
}
3. 手机内部文件存储XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="1. 将asserts下的logo.png保存到手机内部\n2. 读取手机内部图片文件显示"
android:textColor="#ff0000"
android:textSize="15sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btn_if_save"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="save"
android:text="保 存" />
<Button
android:id="@+id/btn_if_read"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="read"
android:text="读 取" />
</LinearLayout>
<ImageView
android:id="@+id/iv_if"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</LinearLayout>
3.2 手机内部文件存储Activity
public class IFActivity extends Activity {
private ImageView iv_if;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_if);
iv_if = (ImageView) findViewById(R.id.iv_if);
}
public void save(View v) throws IOException {
//1. 得到InputStream-->读取assets下的logo.png
//得到AssetManager
AssetManager manager = getAssets();
//读取文件
InputStream is = manager.open("logo.png");
//2. 得到OutputStream-->/data/data/packageName/files/logo.png
FileOutputStream fos = openFileOutput("logo.png", Context.MODE_PRIVATE);
//3. 边读边写
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
//4. 提示
Toast.makeText(this, "保存完成", 0).show();
}
public void read(View v) {// /data/data/packageName/files/logo.png
//1. 得到图片文件的路径
// /data/data/packageName/files
String filesPath = getFilesDir().getAbsolutePath();
String imagePath = filesPath+"/logo.png";
//2. 读取加载图片文件得到bitmap对象
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//3. 将其设置到imageView中显示
iv_if.setImageBitmap(bitmap);
}
}
4. 手机外部文件存储XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et_of_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="存储的文件名" />
<EditText
android:id="@+id/et_of_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="存储的文件内容" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="save"
android:text="保 存" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="read"
android:text="读 取" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="save2"
android:text="保 存2" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="read2"
android:text="读 取2" />
</LinearLayout>
</LinearLayout>
4.2 手机外部文件存储Activity
public class OFActivity extends Activity {
private EditText et_of_name;
private EditText et_of_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_of);
et_of_name = (EditText) findViewById(R.id.et_of_name);
et_of_content = (EditText) findViewById(R.id.et_of_content);
}
public void save(View v) throws IOException {
//1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//2. 读取输入的文件名/内容
String fileName = et_of_name.getText().toString();
String content = et_of_content.getText().toString();
//3. 得到指定文件的OutputStream
//1).得到sd卡下的files路径
String filesPath = getExternalFilesDir(null).getAbsolutePath();
//2).组成完整路径
String filePath = filesPath+"/"+fileName;
//3). 创建FileOutputStream
FileOutputStream fos = new FileOutputStream(filePath);
//4. 写数据
fos.write(content.getBytes("utf-8"));
fos.close();
//5. 提示
Toast.makeText(this, "保存完成", 0).show();
} else {
Toast.makeText(this, "sd卡没有挂载", 0).show();
}
}
public void read(View v) throws Exception {
// 1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 2. 读取输入的文件名
String fileName = et_of_name.getText().toString();
// 3. 得到指定文件的InputStream
// 1).得到sd卡下的files路径
String filesPath = getExternalFilesDir(null).getAbsolutePath();
// 2).组成完整路径
String filePath = filesPath + "/" + fileName;
// 3). 创建FileInputStream
FileInputStream fis = new FileInputStream(filePath);
// 4. 读取数据, 成String
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=fis.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
String content = baos.toString();
// 5. 显示
et_of_content.setText(content);
} else {
Toast.makeText(this, "sd卡没有挂载", 0).show();
}
}
// /storage/sdcard/atguigu/xxx.txt
public void save2(View v) throws IOException {
//1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//2. 读取输入的文件名/内容
String fileName = et_of_name.getText().toString();
String content = et_of_content.getText().toString();
//3. 得到指定文件的OutputStream
//1). /storage/sdcard/
String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//2). /storage/sdcard/atguigu/(创建文件夹)
File file = new File(sdPath+"/atguigu");
if(!file.exists()) {
file.mkdirs();//创建文件夹
}
//3). /storage/sdcard/atguigu/xxx.txt
String filePath = sdPath+"/atguigu/"+fileName;
//4). 创建输出流
FileOutputStream fos = new FileOutputStream(filePath);
//4. 写数据
fos.write(content.getBytes("utf-8"));
fos.close();
//5. 提示
Toast.makeText(this, "保存完成", 0).show();
} else {
Toast.makeText(this, "sd卡没有挂载", 0).show();
}
}
public void read2(View v) throws Exception {
// 1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 2. 读取输入的文件名
String fileName = et_of_name.getText().toString();
// 3. 得到指定文件的InputStream
String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String filePath = sdPath+"/atguigu/"+fileName;
FileInputStream fis = new FileInputStream(filePath);
// 4. 读取数据, 成String
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=fis.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
String content = baos.toString();
fis.close();
// 5. 显示
et_of_content.setText(content);
} else {
Toast.makeText(this, "sd卡没有挂载", 0).show();
}
}
}
5. sqlite数据库存储XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="testCreateDB"
android:text="Create DB" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="testUpdateDB"
android:text="Update DB" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="testInsert"
android:text="Insert" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="testUpdate"
android:text="Update" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="testDelete"
android:text="Delete" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="testQuery"
android:text="query" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="testTransaction"
android:text="Test Transaction" />
</LinearLayout>
5.2 sqlite数据库存储Activity
public class DBActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
}
/*
* 创建库
*/
public void testCreateDB(View v) {
DBHelper dbHelper = new DBHelper(this, 1);
//获取连接
SQLiteDatabase database = dbHelper.getReadableDatabase();
Toast.makeText(this, "创建数据库", 0).show();
}
/*
* 更新库
*/
public void testUpdateDB(View v) {
DBHelper dbHelper = new DBHelper(this, 2);
//获取连接
SQLiteDatabase database = dbHelper.getReadableDatabase();
Toast.makeText(this, "更新数据库", 0).show();
}
/*
* 添加记录
*/
public void testInsert(View v) {
//1. 得到连接
DBHelper dbHelper = new DBHelper(this, 2);
SQLiteDatabase database = dbHelper.getReadableDatabase();
//2. 执行insert insert into person(name, age) values('Tom', 12)
ContentValues values = new ContentValues();
values.put("name", "Tom");
values.put("age", 12);
long id = database.insert("person", null, values);
//3. 关闭
database.close();
//4. 提示
Toast.makeText(this, "id="+id, 1).show();
}
/*
* 更新
*/
public void testUpdate(View v) {
DBHelper dbHelper = new DBHelper(this, 2);
SQLiteDatabase database = dbHelper.getReadableDatabase();
//执行update update person set name=Jack, age=13 where _id=4
ContentValues values = new ContentValues();
values.put("name", "jack");
values.put("age", 13);
int updateCount = database.update("person", values , "_id=?", new String[]{"4"});
database.close();
Toast.makeText(this, "updateCount="+updateCount, 1).show();
}
/*
* 删除
*/
public void testDelete(View v) {
// 1. 得到连接
DBHelper dbHelper = new DBHelper(this, 2);
SQLiteDatabase database = dbHelper.getReadableDatabase();
// 2. 执行delete delete from person where _id=2
int deleteCount = database.delete("person", "_id=2", null);
// 3. 关闭
database.close();
// 4. 提示
Toast.makeText(this, "deleteCount=" + deleteCount, 1).show();
}
/*
* 查询
*/
public void testQuery(View v) {
// 1. 得到连接
DBHelper dbHelper = new DBHelper(this, 2);
SQLiteDatabase database = dbHelper.getReadableDatabase();
// 2. 执行query select * from person
Cursor cursor = database.query("person", null, null, null, null, null, null);
//cursor = database.query("person", null, "_id=?", new String[]{"3"}, null, null, null);
//得到匹配的总记录数
int count = cursor.getCount();
//取出cursor中所有的数据
while(cursor.moveToNext()) {
//_id
int id = cursor.getInt(0);
//name
String name = cursor.getString(1);
//age
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.e("TAG", id+"-"+name+"-"+age);
}
// 3. 关闭
cursor.close();
database.close();
// 4. 提示
Toast.makeText(this, "count=" + count, 1).show();
}
/*
* 测试事务处理
* update person set age=16 where _id=1
* update person set age=17 where _id=3
*
* 一个功能中对数据库进行的多个操作: 要就是都成功要就都失败
* 事务处理的3步:
* 1. 开启事务(获取连接后)
* 2. 设置事务成功(在全部正常执行完后)
* 3. 结束事务(finally中)
*/
public void testTransaction(View v) {
SQLiteDatabase database = null;
try{
DBHelper dbHelper = new DBHelper(this, 2);
database = dbHelper.getReadableDatabase();
//1. 开启事务(获取连接后)
database.beginTransaction();
//执行update update person set age=16 where _id=1
ContentValues values = new ContentValues();
values.put("age", 16);
int updateCount = database.update("person", values , "_id=?", new String[]{"1"});
Log.e("TAG", "updateCount="+updateCount);
//出了异常
boolean flag = true;
if(flag) {
throw new RuntimeException("出异常啦!!!");
}
//执行update update person set age=17 where _id=3
values = new ContentValues();
values.put("age", 17);
int updateCount2 = database.update("person", values , "_id=?", new String[]{"3"});
Log.e("TAG", "updateCount2="+updateCount2);
//2. 设置事务成功(在全部正常执行完后)
database.setTransactionSuccessful();
} catch(Exception e) {
e.printStackTrace();
Toast.makeText(this, "出异常啦!!!", 1).show();
} finally {
//3. 结束事务(finally中)
if(database!=null) {
database.endTransaction();
database.close();
}
}
}
}
5.3 数据库连接类
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context,int version) {
super(context, "atguigu.db", null, version);
}
/**
* 什么时候才会创建数据库文件?
* 1). 数据库文件不存在
* 2). 连接数据库
*
* 什么时候调用?
* 当数据库文件创建时调用(1次)
* 在此方法中做什么?
* 建表
* 插入一些初始化数据
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.e("TAG", "DBHelper onCreate()");
//建表
String sql = "create table person(_id integer primary key autoincrement, name varchar,age int)";
db.execSQL(sql);
//插入一些初始化数据
db.execSQL("insert into person (name, age) values ('Tom1', 11)");
db.execSQL("insert into person (name, age) values ('Tom2', 12)");
db.execSQL("insert into person (name, age) values ('Tom3', 13)");
}
//当传入的版本号大于数据库的版本号时调用
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.e("TAG", "DBHelper onUpgrade()");
}
}
6. 远程服务器存储XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/et_network_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textUri"
android:text="@string/url" >
</EditText>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="1. 测试HttpUrlConnection"
android:textSize="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="testConnectionGet"
android:text="GET请求" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="testConnectionPost"
android:text="POST请求" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="2. 测试HttpClient"
android:textSize="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="testClientGet"
android:text="GET请求" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="testClientPost"
android:text="POST请求" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="3. 测试Volley框架"
android:textSize="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="testVolleyGet"
android:text="GET请求" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="testVolleyPost"
android:text="POST请求" />
</LinearLayout>
<EditText
android:id="@+id/et_network_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:hint="用来显示网络请求返回的结果数据" >
</EditText>
</LinearLayout>
6.2 远程服务器存储Activity
public class NetworkActivity extends Activity {
private EditText et_network_url;
private EditText et_network_result;
private RequestQueue queue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
et_network_url = (EditText) findViewById(R.id.et_network_url);
et_network_result = (EditText) findViewById(R.id.et_network_result);
queue = Volley.newRequestQueue(this);
}
/*
* 使用httpUrlConnection提交get请求
*/
/*
1. 显示ProgressDialog
2. 启动分线程
3. 在分线程, 发送请求, 得到响应数据
1). 得到path, 并带上参数name=Tom1&age=11
2). 创建URL对象
3). 打开连接, 得到HttpURLConnection对象
4). 设置请求方式,连接超时, 读取数据超时
5). 连接服务器
6). 发请求, 得到响应数据
得到响应码, 必须是200才读取
得到InputStream, 并读取成String
7). 断开连接
4. 在主线程, 显示得到的结果, 移除dialog
*/
public void testConnectionGet(View v) {
//1. 显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中...");
//2. 启动分线程
new Thread(){
//3. 在分线程, 发送请求, 得到响应数据
public void run() {
try {
//1). 得到path, 并带上参数name=Tom1&age=11
String path = et_network_url.getText().toString()+"?name=Tom1&age=11";
//2). 创建URL对象
URL url = new URL(path);
//3). 打开连接, 得到HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//4). 设置请求方式,连接超时, 读取数据超时
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(6000);
//5). 连接服务器
connection.connect();
//6). 发请求, 得到响应数据
//得到响应码, 必须是200才读取
int responseCode = connection.getResponseCode();
if(responseCode==200) {
//得到InputStream, 并读取成String
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
final String result = baos.toString();
baos.close();
is.close();
//4. 在主线程, 显示得到的结果, 移除dialog
runOnUiThread(new Runnable() {
@Override
public void run() {
et_network_result.setText(result);
dialog.dismiss();
}
});
}
//7). 断开连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
//如果出了异常要移除dialog
dialog.dismiss();
}
}
}.start();
}
/*
* 使用httpUrlConnection提交post请求
*/
/*
1. 显示ProgressDialog
2. 启动分线程
3. 在分线程, 发送请求, 得到响应数据
1). 得到path
2). 创建URL对象
3). 打开连接, 得到HttpURLConnection对象
4). 设置请求方式,连接超时, 读取数据超时
5). 连接服务器
6). 发请求, 得到响应数据
得到输出流, 写请求体:name=Tom1&age=11
得到响应码, 必须是200才读取
得到InputStream, 并读取成String
7). 断开连接
4. 在主线程, 显示得到的结果, 移除dialog
*/
public void testConnectionPost(View v) {
//1. 显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在加载中...");
//2. 启动分线程
new Thread(new Runnable() {
//3. 在分线程, 发送请求, 得到响应数据
@Override
public void run() {
try {
//1). 得到path
String path = et_network_url.getText().toString();
//2). 创建URL对象
URL url = new URL(path);
//3). 打开连接, 得到HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//4). 设置请求方式,连接超时, 读取数据超时
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//5). 连接服务器
connection.connect();
//6). 发请求, 得到响应数据
//得到输出流, 写请求体:name=Tom1&age=11
OutputStream os = connection.getOutputStream();
String data = "name=Tom2&age=12";
os.write(data.getBytes("utf-8"));
//得到响应码, 必须是200才读取
int responseCode = connection.getResponseCode();
if(responseCode==200) {
//得到InputStream, 并读取成String
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
final String result = baos.toString();
baos.close();
is.close();
//4. 在主线程, 显示得到的结果, 移除dialog
runOnUiThread(new Runnable() {
@Override
public void run() {
et_network_result.setText(result);
dialog.dismiss();
}
});
}
os.close();
//7). 断开连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
dialog.dismiss();
}
}
}).start();
}
/*
* 使用httpClient提交get请求
*/
public void testClientGet(View v) {
//1. 显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中...");
//2. 启动分线程
new Thread(){
//3. 在分线程, 发送请求, 得到响应数据
public void run() {
try {
//1). 得到path, 并带上参数name=Tom1&age=11
String path = et_network_url.getText().toString()+"?name=Tom3&age=13";
//2). 创建HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
//3). 设置超时
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
//4). 创建请求对象
HttpGet request = new HttpGet(path);
//5). 执行请求对象, 得到响应对象
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode==200) {
//6). 得到响应体文本
HttpEntity entity = response.getEntity();
final String result = EntityUtils.toString(entity);
//4. 要主线程, 显示数据, 移除dialog
runOnUiThread(new Runnable() {
@Override
public void run() {
et_network_result.setText(result);
dialog.dismiss();
}
});
}
//7). 断开连接
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
//如果出了异常要移除dialog
dialog.dismiss();
}
}
}.start();
}
/*
* 使用httpClient提交post请求
*/
public void testClientPost(View v) {
//1. 显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中...");
//2. 启动分线程
new Thread(){
//3. 在分线程, 发送请求, 得到响应数据
public void run() {
try {
//1). 得到path
String path = et_network_url.getText().toString();
//2). 创建HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
//3). 设置超时
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
//4). 创建请求对象
HttpPost request = new HttpPost(path);
//设置请求体
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("name", "Tom4"));
parameters.add(new BasicNameValuePair("age", "14"));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
request.setEntity(entity);
//5). 执行请求对象, 得到响应对象
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode==200) {
//6). 得到响应体文本
entity = response.getEntity();
final String result = EntityUtils.toString(entity);
//4. 要主线程, 显示数据, 移除dialog
runOnUiThread(new Runnable() {
@Override
public void run() {
et_network_result.setText(result);
dialog.dismiss();
}
});
}
//7). 断开连接
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
//如果出了异常要移除dialog
dialog.dismiss();
}
}
}.start();
}
/*
* 使用Volley提交get请求
*/
/*
1. 创建请求队列对象(一次)
2. 创建请求对象StringRequest
3. 将请求添加到队列中
*/
public void testVolleyGet(View v) {
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中...");
//创建请求对象StringRequest
String path = et_network_url.getText().toString()+"?name=Tom5&age=15";
StringRequest request = new StringRequest(path, new Response.Listener<String>() {
@Override
public void onResponse(String response) {//在主线程执行
et_network_result.setText(response);
dialog.dismiss();
}
}, null);
//将请求添加到队列中
queue.add(request);
}
/*
* 使用Volley提交post请求
*/
public void testVolleyPost(View v) {
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中...");
//创建请求对象StringRequest
String path = et_network_url.getText().toString();
StringRequest request = new StringRequest(Method.POST, path, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
et_network_result.setText(response);
dialog.dismiss();
}
}, null){
//重写此方法返回参数的map作为请求体
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("name", "Tom6");
map.put("age", "16");
return map;
}
};
//将请求添加到队列中
queue.add(request);
}
}
7.AndroidManifest.xml
<!-- 操作sd卡 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 联网 -->
<uses-permission android:name="android.permission.INTERNET"/>