android常用代码总结(二)
今天起了一个大早(相对于我以前),时不我待,没有多少时间可以浪费了,继续总结
先说说两种方式的网络操作吧,当然这些代码我都是看过很多类似的代码之后,觉得总结得非常之好的,拿来mark一下
一.java.net包中的HttpUrlConnection
// Get方式请求
public static void requestByGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
//新建一个URL对象
URL url = new URL(path);
//打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
//开始连接
urlConn.connect();
//判断请求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
//获取返回的数据
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_GET, "Get方式请求成功,返回数据如下:");
Log.i(TAG_GET, new String(data, "UTF-8"));
} else {
Log.i(TAG_GET, "Get方式请求失败");
}
//关闭连接
urlConn.disconnect();
}
Post方式
// Post方式请求
public static void requestByPost() throws Throwable {
String path = "https://reg.163.com/logins.jsp";
//请求的参数转换为byte数组
String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
+ "&pwd=" + URLEncoder.encode("android", "UTF-8");
byte[] postData = params.getBytes();
//新建一个URL对象
URL url = new URL(path);
//打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// Post请求必须设置允许输出
urlConn.setDoOutput(true);
// Post请求不能使用缓存
urlConn.setUseCaches(false);
//设置为Post请求
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
//配置请求Content-Type
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencode");
//开始连接
urlConn.connect();
//发送请求参数
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
//判断请求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
//获取返回的数据
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_POST, "Post请求方式成功,返回数据如下:");
Log.i(TAG_POST, new String(data, "UTF-8"));
} else {
Log.i(TAG_POST, "Post方式请求失败");
}
}
二.org.apache.http包中的HttpGet和HttpPost类
get方式
// HttpGet方式请求
public static void requestByHttpGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
//新建HttpGet对象
HttpGet httpGet = new HttpGet(path);
//获取HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
//获取HttpResponse实例
HttpResponse httpResp = httpClient.execute(httpGet);
//判断是够请求成功
if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
//获取返回的数据
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpGet方式请求成功,返回数据如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpGet方式请求失败");
}
}
Post方式
// HttpPost方式请求
public static void requestByHttpPost() throws Exception {
String path = "https://reg.163.com/logins.jsp";
//新建HttpPost对象
HttpPost httpPost = new HttpPost(path);
// Post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "helloworld"));
params.add(new BasicNameValuePair("pwd", "android"));
//设置字符集
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
//设置参数实体
httpPost.setEntity(entity);
//获取HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
//获取HttpResponse实例
HttpResponse httpResp = httpClient.execute(httpPost);
//判断是够请求成功
if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
//获取返回的数据
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpPost方式请求成功,返回数据如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpPost方式请求失败");
}
}
再谈谈文件操作吧,真的是毫无逻辑了,而且这些都是一些引子,引导我在今后的学习中不断扩展.言归正传,文件分两类,一类是手机内存,一类是SD Card,这两种文件读写方式存在着差异,具体情况请看下面的代码:
一. 手机内存
private String read() {
try {
FileInputStream fis = openFileInput(FILE);
byte[] buffer = new byte[1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder("");
while ((hasRead = fis.read(buffer))> 0) {
sb.append(new String(buffer, 0, hasRead));
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void write(String content)
{
try
{
// 以追加模式打开文件输出流
FileOutputStream fos = openFileOutput(FILE, MODE_APPEND);
// 将FileOutputStream包装成PrintStream
PrintStream ps = new PrintStream(fos);
// 输出文件内容
ps.println(content);
ps.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
二. SD card
private String read() {
// 如果手机插入了SD卡,而且应用程序具有访问SD的权限
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 获取SD卡的目录
File sdDirFile = Environment.getExternalStorageDirectory();
//获取指定文件对应的输入流
FileInputStream fis = new FileInputStream(sdDirFile.getCanonicalPath()+ FILE);
//将指定输入流包装成BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder("");
String line = null;
while ((line =br.readLine())!=null) {
sb.append(line);
}
return sb.toString();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void write(String context){
try {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdDir = Environment.getExternalStorageDirectory();
File targetFile = new File(sdDir.getCanonicalPath()+ FILE);
RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
raf.seek(targetFile.length());
raf.write(context.getBytes());
raf.close();
}
} catch (Exception e) {
}
}
}
等我实际在操练一番,再继续总结我所学到的东西吧,这里很多经验都来自open 经验库,感谢那些分享的人