package org.sunnysolong.net;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
/**
* Wap登录返回测试
* Title: JavaTech<br>
* Description: <br>
* Copyright: Copyright (c) 2011 <br>
* Create DateTime: Nov 14, 2011 8:55:24 PM <br>
* @author wangmeng
*/
public class WapQuery {
private static String URL_LINK = "http://192.168.1.147/t3/wap/index.php";
// http://192.168.1.147/t3/wap/index.php?mod=topic&code=myhome
// 转向URL:http://192.168.1.147:80/t3/wap/index.php
private static final HttpClient HTTP_CLIENT = new HttpClient();
private static Cookie[] cookies;
private static GetMethod login;
private static GetMethod home;
/**
* 输入流转换成字符串
* @param is: 输入流
* @return 字符串对象
*/
private static String InputStreamToString(InputStream is){
BufferedReader reader = null;
StringBuffer responseText = null;
String readerText = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
responseText = new StringBuffer();
readerText = reader.readLine();
while(readerText != null){
responseText.append(readerText);
responseText.append(System.getProperty("line.separator"));
readerText = reader.readLine();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseText.toString();
}
/**
* 将cookie写入指定文件
* @param cookies: cookie
* @param fileName: 文件名
*/
private static void write(Cookie[] cookies, String fileName){
try {
String path = System.getProperty("user.home") + "\\" + fileName;
File file = new File(path);
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for(Cookie c : cookies){
bw.append(c.toString());
bw.append(System.getProperty("line.separator"));
}
bw.flush();
bw.close();
Runtime.getRuntime().exec("explorer " + path + "");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 登录
*/
private static void login(){
try {
//指定链接设定请求方式
login = new GetMethod(URL_LINK);
//入参
NameValuePair mod = new NameValuePair("mod", "login");
NameValuePair code = new NameValuePair("code", "dologin");
NameValuePair username = new NameValuePair("username", URLEncoder.encode("wangli@qq.com", "UTF-8"));
NameValuePair password = new NameValuePair("password", URLEncoder.encode("123456", "UTF-8"));
NameValuePair iswap = new NameValuePair("iswap", "1");
NameValuePair cityID = new NameValuePair("cityID", URLEncoder.encode("755", "UTF-8"));
NameValuePair city = new NameValuePair("city", URLEncoder.encode("深圳", "UTF-8"));
NameValuePair[] params = new NameValuePair[]{mod, code, username, password, iswap, cityID, city};
//设参
login.setQueryString(params);
//禁用重定向
login.setFollowRedirects(false);
//执行请求并返回状态码
int statusCode = HTTP_CLIENT.executeMethod(login);
//转向URL:http://192.168.1.147:80/t3/wap/index.php
if (statusCode != HttpStatus.SC_OK) {
System.err.println("LOGIN_ERROR >>> " + login.getStatusLine());
}
System.out.println("LOGIN_RESPONSE >>>" + InputStreamToString(login.getResponseBodyAsStream()));
//设定全局cookie
cookies = HTTP_CLIENT.getState().getCookies();
//记录cookie
write(cookies, "login-cookie.txt");
} catch (UnsupportedEncodingException e) {
System.err.println("(LOGIN) " + e.getMessage());
} catch (HttpException e) {
System.err.println("(LOGIN) " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("(LOGIN) " + e.getMessage());
} finally{
//释放连接
login.releaseConnection();
}
}
/**
* 主页
*/
private static void home(){
try {
//指定链接设定请求方式
home = new GetMethod(URL_LINK);
//入参、设参
home.setQueryString("mod=topic&code=myhome");
//记录cookie
write(HTTP_CLIENT.getState().getCookies(), "home-cookie.txt");
//添加cookie
HTTP_CLIENT.getState().addCookies(cookies);
//执行请求并返回状态码
int statusCode = HTTP_CLIENT.executeMethod(home);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("HOME_ERROR >>>" + home.getStatusLine());
}
//再次记录cookie
write(HTTP_CLIENT.getState().getCookies(), "access-cookie.txt");
System.out.println("HOME_RESPONSE >>>" + InputStreamToString(home.getResponseBodyAsStream()));
} catch (HttpException e) {
System.err.println("(HOME) " + e.getMessage());
} catch (IOException e) {
System.err.println("(HOME) " + e.getMessage());
} finally {
home.releaseConnection();
}
}
public static void main(String[] args) {
//登录
login();
//转向主页
home();
/**
* 说明:查看login-cookie.txt和home-cookie.txt中记录的cookie是否完全一致,是则表示会话信息保留完整。
* access-cookie.txt中记录的是第二次请求返回的cookie,用来与全局记录的cookie做信息对比。
*/
}
}
查看官方的解释:
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progressand Result, and 4 steps, called begin, doInBackground, processProgress and end.
Usage:
AsyncTask 是abstract class必须被子类继承使用。至少要重写一个方法:(doInBackground(Params...)), 经常还要重写另一个方法:(onPostExecute(Result).)
demo:
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
创建后,使用起来,非常简单:
new DownloadFilesTask().execute(url1, url2, url3);
在网上搜了一下,这篇文章讲解的不错。
http://blog.csdn.net/zuolongsnail/article/details/6394055
在Android开发中经常会需要用的列表,你可以用ListActivity,或者ListView,甚至其他方法。
用ListView相对来说更灵活。下边是ListView简单实现代码:
显示java文件:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class aGirlGallery extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 绑定Layout里面的ListView
ListView list = (ListView) findViewById(R.id.lv);
// 生成动态数组,加入数据
ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < 10; i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.icon);// 图像资源的ID
map.put("ItemTitle", "Level " + i);
listItem.add(map);
}
// 生成适配器的Item和动态数组对应的元素
SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 数据源
R.layout.list_items,// ListItem的XML实现
// 动态数组与ImageItem对应的子项
new String[] { "ItemImage", "ItemTitle" },
// list_items中对应的的ImageView和TextView
new int[] { R.id.ItemImage, R.id.ItemTitle });
// 绑定数据源
list.setAdapter(listItemAdapter);
// 点击事件
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView< ?> arg0, View arg1, int position,
long id) {
//do something?
}
});
// 长按事件
list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
//do something?
}
});
}
// 长按菜单响应函数
@Override
public boolean onContextItemSelected(MenuItem item) {
//do something?
return super.onContextItemSelected(item);
}
}
然后是main.xml:
< ?xml version="1.0" encoding="utf-8"?><linearlayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <listview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lv" /></linearlayout>
list_items.xml:
< ?xml version="1.0" encoding="utf-8"?><relativelayout android:id="@+id/RelativeLayout01" android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:paddingLeft="10dip" android:paddingRight="10dip"> <imageview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ItemImage" /> <textview android:layout_toRightOf="@id/ItemImage" android:paddingTop="10dip" android:layout_height="wrap_content" android:textSize="18dip" android:layout_width="fill_parent" android:id="@+id/ItemTitle" /></relativelayout>